barjo
barjo

Reputation: 143

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?

Upvotes: 0

Views: 2187

Answers (3)

Ares
Ares

Reputation: 1366

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.

Upvotes: 2

deceze
deceze

Reputation: 522125

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';
}

Upvotes: 2

supra28
supra28

Reputation: 1636

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.

Upvotes: 0

Related Questions