Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimization - For statement and variable declarations

Here is a quotation from MDN about 'for' statement :

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

So when I write this kind of code :

for(var i = 0; i < 10; i++) {
    for(var j = 0; j < 10; j++) {
        // ...
    }
}

At each iteration of the outer loop I declare the variable j, which was already declared right ?

So is it better to write something like this :

for(var i = 0, j = 0; i < 10; i++) {
    for(j = 0; j < 10; j++) {
        // ...
    }
}

... or we do not care?

like image 447
Cinn Avatar asked Jun 03 '15 13:06

Cinn


1 Answers

The behavior this quote refers to is called hoisting and is important to know in JavaScript.

Here's how the MDN explains it:

Because 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. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved 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 clearer.

There's absolutely no gain in having both vars being declared in the first loop. It's only confusing. It's the same for the JS engine, but the other developers reading this code will wonder why j is declared at an unexpected location.

Now, if you're disturbed by the fact your variable exists before (with an undefined value) and after the loop where you use it, rejoice: there's a new declaration type coming with ES6: let, which scopes the variable to the block.

for(let i = 0; i < 10; i++) {
    for(let j = 0; j < 10; j++) {
        // ...
    }
}

Beware: compatibility of let

For now, please use the standard form that everybody expects:

for(var i = 0; i < 10; i++) {
    for(var j = 0; j < 10; j++) {
        // ...
    }
}

The convention, in such a case, is that i and j won't be used outside of their loop. When (and only in this case) you want to use i or j after (for example there's a break in the loop), use this:

var i, j;
for(i = 0; i < 10; i++) {
    for(j = 0; j < 10; j++) {
        // ...
    }
}
// use i and j here
like image 91
Denys Séguret Avatar answered Sep 24 '22 01:09

Denys Séguret