I looked up that variable scope is not isolated
Where did you look that up? Every JS tutorial and help page makes it clear that variables declared with var
have function scope.
I'm a little bit puzzled by the seeming fascination of beginning JS programmers with the questions of scoping and hoisting. The correct approach is:
Declare your variables at the top of your function where they belong. Virtually all style guides, if you are following one, require this anyway. Virtually all linters, if you are using one, will, or can be configured to, enforce this.
Spend the time you had planned to use for worrying about hoisting, variable scoping, and temporal dead zones instead to read a book, walk your dog, or actually do useful coding.
Live a long and happy life.
If for some reason it is important for you to have variables scoped to a block (anything inside {}
, such as the body of an if
or for
statement), then yes, use let
. In the real world, I think you'll find such cases to be quite few, unless you are writing huge functions which contain dozens or hundreds of lines, which is not good practice to begin with. In this case, again follow best practice and declare all your variables at the top of the block.
If you don't have let
available, and want to use another identically-named variable inside a block, then what about just using another variable? For instance, in the example you gave, inside the if
block use test1
instead of test
. This is actually how babel does it under the covers. It transpiles
function f() { var x; { let x; } }
into
function f() { var x; { var _x; } }
^^
You will see it has renamed the inner x
to _x
.
Your question is essentially equivalent to wondering why it hurts when you stick pins in your eyes. Instead of worrying about different kinds of pins to stick in your eyes, or what the biological mechanism of the resulting pain is, why not stop sticking the pins in your eyes to start with?