And I thought I understood the scope

Can someone tell me why the last logon of "x" is 0, not 1. I thought because it was declared outside of a function that has a global scope, and then in the function the value is 1, and this value will remain global? I know that the first value of "x" inside the function is global, since any variable declared without the var keyword becomes a property of the window object. Many thanks

var x = 0; //global variable function y(){ x = 1; log("1. %n ", x);//1. 1 var x = 2; log("2. %n ", x);//2. 2 } y(); log("3. %n ", x);//3. 0 
+7
javascript
source share
3 answers

The var statement undergoes a lift, when your code is evaluated, it looks like this:

 var x = 0; //global variable function y(){ var x; // local!! x = 1; log("1. %n ", x);//1. 1 x = 2; log("2. %n ", x);//2. 2 } y(); log("3. %n ", x);//3. 0 

Before executing y , a new execution context is set up, and Variable Instantiation is executed before the function is executed.

This is one of the reasons why JSLint recommends only one var statement for each function, so that it resembles what is actually happening.

+6
source share

The variable x inside the function is created immediately when the function is executed, and not only when the line with the variable expression has reached:

If a variable operator occurs inside a FunctionDeclaration, the variables are defined using the local scope function in this function [...]. Variables are created when you enter a runtime. [...] At creation, variables are initialized undefined . [...]

You can see that x initially undefined when adding a log call before the first assignment:

 function y(){ log("0. " + x);//0. undefined x = 1; log("1. " + x);//1. 1 var x = 2; log("2. " + x);//2. 2 } 

This means that both assignments within the function refer to x in the function-local region, and not to x in the global region.

+5
source share

I think, but I cannot confirm through the ecmascript specification that the string "var x = 2" is checked during the definition of the function, and the local region "x" is applied to the entire function, and not just after "var x" in the function.

Here's a simpler test case (tested with jsdb ):

 js>x = 0; 0 js>function foo(k) { x=k; } js>function bar(k) { var x=k; } js>function baz(k) { x=k; var x=2; } js>foo(1) js>x 1 js>bar(2) js>x 1 js>baz(3) js>x 1 

You will notice that the only function that affects the global "x" is foo() . The bar() function obviously only affects local x. But the baz() function only affects local x. You might think that assignment x=k; will affect global x, as it happens "before" the next statement var x = 2; , which explicitly affects the local variable x. But I am sure that if you execute var x in a function, the interpreter sees it and applies it to all applications of x in this area. The same situation as yours.

+1
source share

All Articles