Details
-
Type:
New Feature
-
Status:
Closed
-
Priority:
Major
-
Resolution: Fixed
-
Affects Version/s: None
-
Fix Version/s: JAVASCRIPT-1.3
-
Component/s: JavaScript
-
Labels:None
-
Number of attachments :
Description
Compare:
var x = 1;
function fun() {
print(x); // undefined
if (false) {
var x = 42;
}
}
fun();
and
var x = 1;
function fun() {
print(x); // 1
if (false) {
x = 42;
}
}
fun();
See
*Description:
One of the sources of most confusion for JavaScript beginners is scoping. The reason scoping is so confusing in JavaScript is because it looks like a C-family language but doesn't behave the same way. Indeed C, and the rest of the C family, has block-level scope. When control enters a block, such as an if statement, new variables can be declared within that scope, without affecting the outer scope. This is not the case in JavaScript where only functions create a new scope.
The following code snippet illustrates this rule:
Whereas the following code snippet is correct: