Thursday, April 16, 2015

javascript var or without var when declaring variables

If you use var the variable is declared within the scope you are in (e.g. of the function). If you don't use var, the variable bubbles up through the layers of scope until it encounters a variable by the given name or the global object (window, if you are doing it in the browser), where it then attaches. The var a = 'x' is in the scope of test function only. It won't change the value of a which is out side the function. Without var inside the test function, the variable a is actually same variable a outside function test. Here is another example. If the first and the third line is removed, it is the same result. The only difference is that the variable app is only available inside the anonymous function, so that it won't pollute the global context and eliminate the possibility of variable name conflicting.

http://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional

No comments:

Post a Comment