4 ms·
Ask HN: What is the scope of a variable in javascript?
In the book "Secrets of the JavaScript Ninja" the following is stated: if the line "var b = 2;" occurs somewhere half way down a function body, then the scope of that variable begins with that line (see Figure 3.6 in the book). As we all know, the declaration part "var a" will be hoisted to the top of the function body, whereas the "= 1" part will not. Wikipedia defines scope as follows: "In computer programming, a scope is the context within a computer program in which a variable name or other identifier is valid and can be used, or within which a declaration has effect." Doesn't that mean that the scope of the variable b in the example begins at the place where "var b" is hoisted to? It is true that b's value equals "undefined" until b is set to 2. But debuggers such as Chrome's developer tool dutifully list b under "Scope Variables" right from the top of the function. Doesn't that contradict what the book says?