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
  • 3,016
  • 8
  • 43
  • 65

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
  • 7,210
  • 10
  • 45
  • 76
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,413
  • 1
  • 21
  • 33
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
  • 55,303
  • 33
  • 133
  • 164