JS: var Name Scope
function-level scope
Name declared with var has scope to nearest outer function's curly bracket {}.
This variable scoping rule is called function-level scope.
name scope means where the name can be seen. (that is, have meaning.)
// Name declared with var has scope to nearest outer function's curly bracket {}. function f() { var n = 3; { var n = 4; } return n; } console.log(f()); // prints 4
If a var declaration is not inside function, then its scope is global. 〔see Global Variable〕
Note: the
function-level scope
applies only for variable declared with var. It does not apply to variable declared with
let or const.
〔see let Declaration〕
Using Function to Emulate Block Scope
In pre-JS2015 code, you will often see that a function is used purely for the purpose of containing variable inside as local variables, like this:
(function(){
var x; // local var x
// …
}());
This will create a function, and immediately evaluate it. Here's a example.
function f() { var n = 3; (function () { var n = 4; })(); return n; } console.log(f()); // prints 3
Function Scope as Namespace
JavaScript pre-JS2015 does not have modules or namespace. One hack to achieve namespace is wrapping the entire source code of your package inside a function. Like this:
(function nicePackage() { // your source code here })();
This way, when your package/file is loaded, it only introduces one name into the global space.