The behavior this quotation refers to is called hoisting and is important to know in JavaScript.
Here MDN explains this :
Since variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. It also means that the variable may appear to be used before it is declared. This behavior is called "lifting" because it appears that the variable declaration moves to the top of the function or global code.
The reason you donβt declare all your variables at the top of the function is because their localization makes the code more understandable.
There is absolutely no gain when both vars are declared in the first loop. This is only embarrassing. This is the same for the JS engine, but other developers reading this code wonder why j declared in an unexpected place.
Now, if you are concerned about the fact that your variable exists before (with the value undefined ) and after the cycle in which you use it, rejoice: there is a new type of declaration with ES6: let , which binds the variable to a block.
for(let i = 0; i < 10; i++) { for(let j = 0; j < 10; j++) {
Beware: let compatibility
For now, please use the standard form everyone expects:
for(var i = 0; i < 10; i++) { for(var j = 0; j < 10; j++) {
the convention , in this case, is that i and j will not be used outside their cycle. When (and only in this case) you want to use i or j after (for example, there is a gap in the loop), use this:
var i, j; for(i = 0; i < 10; i++) { for(j = 0; j < 10; j++) {
source share