Variable shading and testing for existence prior to assignment in javascript

In the following code snippet, I declare a global variable, and then check its presence inside the function.

<script> x = 5; $(function() { var x = x || 3; console.log(x); // prints 3 }); </script> 

This behaves differently:

 <script> x = 5; $(function() { var y = x || 3; console.log(y); // prints 5 }); </script> 

I expect that in the first example, declaring a variable in the inner scope will detect that x already exists in the global scope and takes on a value. Why is the first example 3?

In particular, I recently wrote code that checks var _gaq = _gaq || [] var _gaq = _gaq || [] in the jQuery readiness area and was baffled when nothing got into Google Analytics.

+4
source share
3 answers

You are looking for x in the wrong area. Due to the climb variable, var x actually defined a local variable x with an undefined value before checking x || 3 x || 3 :

 var x = x || 3; 

actually:

 var x = undefined; x = x || 3; 

Just change it to search for x of the window object:

 var x = window.x || 3; 
+3
source

The first log example is 3, because any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope. any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope.

So, in the first case, when a local x is assigned, since it is not initialized, it is assigned 3.

While in the second case, x refers to the global variable x , since x not declared inside the function.

Instead, if you try this

 <script> x = 5; $(function() { x = x || 3; console.log(x); }); </script> 

OR

 <script> x = 5; $(function() { var x = window.x || 3; console.log(x); }); </script> 

You will get the expected result 5 .

In addition, unlike C and its family (which has a block level scope ), JavaScript has a functional level scope . Blocks, such as if statements, do not create a new scope. Only functions create a new area.

So, if I wrote something like

 #include <stdio.h> int main() { int x = 1; printf("%d, ", x); // 1 if (1) { int x = 2; printf("%d, ", x); // 2 } printf("%d\n", x); // 1 } 

OUTPUT: 1,2,1

compared with

 var x = 1; console.log(x); // 1 if (true) { var x = 2; console.log(x); // 2 } console.log(x); // 2 

OUTPUT: 1,2,2

Check out this excellent JavaScript blog post, Scoping and Histing , to better understand it.

+1
source

var x in the function declares that x is local to the function, so in x || 3 x || 3 x is not global x and therefore undefined since it was not initialized.

In var y = x || 3; var y = x || 3; x is global x, since there is no x local function.

0
source

All Articles