To understand what value a variable has in JavaScript, we need to understand some concepts such as scope and name resolution order.
JavaScript has two scopes; one is program level and the other one is function level. Unlike in C,C++ or Java, JavaScript has no block level scope. So a variable defined in a if block will still be available outside. For example, the below example:
var foo = 1; function bar() { if (true) { var foo = 10; } alert(foo); } bar();
The alert will display 10 since the variable foo defined in the if block can been seen by the alert() function.
Next we need to understand the name resolution. Let's first look one example:
function a (x) { return x * 2; } var a; console.log(a);
What will be the output? Will it be undefined? The answer is it will print out the function a and its body. Why? This is because in JavaScript, a name enters into the scope with following four ways:
- Language-defined: All scopes are, by default, given the names
this
andarguments
. - Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
- Function declarations: These are of the form
function foo() {}
. - Variable declarations: These take the form
var foo;
.
The name resolution order is also the order listed above, that is function declaration comes before variable declaration. Also In general, if a name has already been defined, it is never overridden by another property of the same name.
So for above example, function a and the variable a has the same time, according to the name resolution order above, the function declaration will take precedence and it will not be overridden by the variable definition.That's why we have the above example to print out the function body instead of undefined.