Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring var inside Javascript for loop declaration

I'm sure I've read a discussion on SO about this but can't find it. Simply, are there cons to declaring a for loop's increment inside the loop's declaration? What is the difference between this:

function foo() {
    for (var i=0; i<7; i++) {
        // code
    }
}

...and this:

function foo() {
    var i;
    for (i=0; i<7; i++) {
        // code
    }
}

Since JS has function scope, either should be fine, right? Are there edge cases where the former approach would cause problems?

If they are identical, why is Crockford/JSLint all, "No way dawg," about it?

like image 766
Benjamin Allison Avatar asked Apr 18 '12 00:04

Benjamin Allison


1 Answers

These are exactly the same. All local variables in javascript have function scope which means they are alive for the entire function they are declared in. This is often counter intuitive at first as most curly brace languages scope the life time of the variable to the block they are declared in.

A portion of Javascript developers very much prefer the second form. The rationale is that since all variables have function scope, you should declare them at the function level to make the life time explicit even for those not familiar with Javascript. This is just a style though and by no means a hard rule

EDIT

Note that with the introduction of ES6 let, you can now use let inside your loop for real block-scoped variable more details

for(let i = 1; i <= 5; i++) {
   setTimeout(function(){
       console.log('Value of i : ' + i);
   },100);
}
like image 81
JaredPar Avatar answered Nov 06 '22 12:11

JaredPar