Fastest way is to use coalescing operator:
rlPrice = $('#rl option:selected').data("unit-price") || 0;
See this link
Question
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;
Solution
Fastest way is to use coalescing operator:
rlPrice = $('#rl option:selected').data("unit-price") || 0;
See this link
OTHER TIPS
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")
Your if..else
statement is precised using the ?:
opertor.
rlPrice = $('#rl option:selected').data("unit-price") == undefined
? 0
: $('#rl option:selected').data("unit-price");