Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Name resolution order in JavaScript

  sonic0002        2013-07-10 01:29:28       7,088        0    

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:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. 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.

JAVASCRIPT  SCOPE  NAME RESOLUTION 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  0 COMMENT


No comment for this article.