I saw a piece of code in a book, which is as follows:
x = 10;
if(x ==10) { // start new scope
int y = 20; // known only to this block
x = y * 2;
}
From Mozilla's A re-introduction to JavaScript (JS Tutorial)
An important difference between JavaScript and other languages like Java is that in JavaScript, blocks do not have scope; only functions have a scope. So if a variable is defined using var in a compound statement (for example inside an if control structure), it will be visible to the entire function. However, starting with ECMAScript 2015, let and const declarations allow you to create block-scoped variables.
Given the examples for var and how they differ from those for int and const, we can gather that, in JavaScript, a variable declared with var is visible outside of its immediate "scope," as we would typically use the word in other languages.
In the example given, something declared with var in a for-loop is available from anywhere in the function, both before and after the for-loop in which it was declared.
// myVarVariable *is* visible out here
for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) {
// myVarVariable is visible to the whole function
}
// myVarVariable *is* visible out here
This is in contrast to anything declared with let and const, which are limited to the block in which they are declared, in much the way variables are limited to the immediate scope of a single set of curly braces { } in other languages.
Moral of the story: be careful with var if you are used to other languages. It is much more powerful and visible than you would expect.