0

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?

barjo
  • 143
  • 1
  • 9
  • 3
    It does not make sense to declare a variable with `var` inside an `if` statement because the variable will be hoisted to the function scope anyway. You can do it with `let` or `const` but the variable is only defined within the enclosing block. – Pointy May 28 '18 at 13:05

3 Answers3

2

In my opinion there is not such thing as an optional declaration. You declare the variable and then the assignment can be optional if you can call it that (better say conditional). Finally check for null.

Also let const and var are different things: let has a block scope, const is read only and block scoped and finally var has a function scope. There is a lot more involved in using them safely cause hey, it's JS, but that's is the summary.

Ares
  • 1,356
  • 1
  • 9
  • 22
2

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';
}
deceze
  • 510,633
  • 85
  • 743
  • 889
0

If you don't want the else block you can do this

let makeVariable = variableNotMade && foo

but this will set makeVariable to false. So, if this is not what you specifically want, you should use deceze♦ method.

supra28
  • 1,646
  • 10
  • 17