jshint: It *is* necessary to initialize 'x' to 'undefined'.

See following simplified test

for( var i = 0; i < 10; i++ )
{
    var x = undefined;

    if( i % 2 === 0 )
    {
        x = null;
    }

    if( x === undefined )
    {
        console.log( i );
    }
}

the output is as one can easily guess:

1
3
5
7
9

jshint complains that: test.js: line 3, col 9, It’s not necessary to initialize ‘x’ to ‘undefined’.

However,

for( var i = 0; i < 10; i++ )
{
    var x;

    if( i % 2 === 0 )
    {
        x = null;
    }

    if( x === undefined )
    {
        console.log( i );
    }
}

will produce on V8 (chrome and node) only

1

As x will not be reset to undefined on every loop interation.

( jshint v2.4.2 )

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 19 (4 by maintainers)

Most upvoted comments

👍 it is not an error to initialize a variable to undefined

Furthermore:

for (var i=0; i<5; i+=1) { 
    var x = undefined; 
    console.log(x); 
    [some other code]
    x = 5; 
}

result: 5x undefined

for (var i=0; i<5; i+=1) { 
    var x; 
    console.log(x); 
    [some other code]
    x = 5; 
}

result: 1x undefined 4x 5

Ok, declaring a variable inside a for loop is a bad practice, but it’s NOT signaled by JSHint…