Search code examples
javascriptvariablesvar

In JS what is the benefit of declaring a variable name before assigning a value to it?


Normally I would declare a variable with the value like so:

var foo = "I am foo";

But recently I have seen the variable name declared first, and then a value assigned later like so: var foo;

foo = "I am foo";

What is the benefit of doing it this way?


Solution

  • No "benefit" in particular. But certain situations call for it, most notably conditional declarations:

    var foo;
    
    if (bar) {
        foo = 'baz';
    } else {
        foo = 42;
    }
    

    Using var both times within the if..else would be in error or at least misleading. If you use let instead of var, it would even scope the variable incorrectly.