1

How can I write shorthand for an IF statement without else?

var val = score == 10 ? win;
console.log(val) //basically I want to update `val` only with the if statement.
Becky
  • 5,467
  • 9
  • 40
  • 73

3 Answers3

3

You can use a logical and:

var val;
score == 10 && (val = win);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

why not simply

var val = score == 10 ? win : val;

or

var score = 10, val=10, win=11;
score == 10 && ( val = win )
alert( val ); //after this output will be 11
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Well, if it shouldn't update the val variable if the statement doesn't return true, just use the val variable as the else:

var val = score == 10 ? win: val;
console.log(val)

You could also use:

score == 10 && var val = win;

But I would suggest just using the if statement for readability:

if(score == 10) 
    var val = win;
Jacques Marais
  • 2,666
  • 14
  • 33