Search code examples
javascriptif-statementecmascript-6constantslet

How to use if statement to declare a new variable with ES6? JavaScript


How can I optionally declare a variable using let or const? For example it would be possible to do:

if (variableNotMade) {
  var makeVariable
}

But how can this be achieved using let or const instead of var?
A similar post here shows that it's possible to do:

let makeVariable = variableNotMade ? foo : bar

Although this approach only really works if you have an else.
Is there a suitable way to achieve this or should a different approach be taken?


Solution

  • You should not "conditionally create variables". You can conditionally assign values to a variable, but not conditionally create it.

    Take this example and assume it would work as you expect:

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

    So what if foo is false, then bar isn't being created, then alert(bar) would raise an error about an undefined variable?! No, this is insane.

    That's why var declarations will be hoisted and the variable will exist, merely with an undefined value. And it's why let and const are explicitly block scoped; they will exist inside their block, and they won't exist outside their block. So you can never get into a situation in which a "conditionally created variable" doesn't exist.

    What you want is probably:

    let foo;
    
    if (bar) {
        foo = 'baz';
    }