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;

3 Answers 3

3

Fastest way is to use coalescing operator:

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

See this link

Sign up to request clarification or add additional context in comments.

3 Comments

+1 null coalescing this is the opt word. Thanks for letting me know this and I like this clean approach.
Note that the || js operator is not perfectly equal to c#'s ??, see clarifications on the linked page
@user1671639 you mean apt word??
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")

Comments

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.