WoJ
WoJ

Reputation: 29987

How to declare a variable in a ternary expression?

I need to set i depending on a condition:

let i = null
nightmode === true ? i = 1 : i = 0

Is it possible to declare i within the ternary expression, or does it have to be in outside of it (to handle scoping)?

Upvotes: 4

Views: 6678

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use the ternary directly as assignment for the value.

let i = nightmode === true ? 1 : 0;

Upvotes: 5

Virginia
Virginia

Reputation: 737

I think your variable i needs to be outside of it, although it is possible to set i in the following manner:

let nightmode = true;
let i = (nightmode === true) ? 1 : 0
console.log(i);

Upvotes: 0

Related Questions