0

I am looking to assign rlPrice to either 0 (if undefined) or to the defined price which would be available. This below will do it ok.

if($('#rl option:selected').data("unit-price") == undefined){
    rlPrice = 0;
else{
    rlPrice = $('#rl option:selected').data("unit-price");
}

However is there a way to do it with ternary operators?

rlPrice = $('#rl option:selected').data("unit-price") OR 0;
Pierce McGeough
  • 2,918
  • 8
  • 40
  • 64

3 Answers3

3

Fastest way is to use coalescing operator:

rlPrice = $('#rl option:selected').data("unit-price") || 0;

See this link

Community
  • 1
  • 1
Teejay
  • 6,913
  • 10
  • 43
  • 72
0

The ternary operator has the form

d = a ? b : c; 

Effectively, it means if a is true, then assign b to d, otherwise assign c to d.

So, replacing the real expressions in the above statement:

rlPrice = $('#rl option:selected').data("unit-price") == undefined?0:$('#rl option:selected').data("unit-price")
RAM
  • 2,338
  • 1
  • 20
  • 32
0

Your if..else statement is precised using the ?: opertor.

rlPrice = $('#rl option:selected').data("unit-price") == undefined 
           ? 0 
           : $('#rl option:selected').data("unit-price");
Praveen
  • 53,079
  • 32
  • 129
  • 156