Strong Like Bull
Strong Like Bull

Reputation: 11297

how to optimize this piece of JS code?

Sorry JS newbie here:

    if (message.notify_one_day_out){
        $("#data\\[User\\]\\[notify_one_day_out\\]").val("1");
    }
    else{
        $("#data\\[User\\]\\[notify_one_day_out\\]").val("0");
    }  

The above code feels sloppy. How can I condense it? I know this is development fundamentals but can I do something like:

$("#data\\[User\\]\\[notify_one_day_out\\]").val(message.notify_one_day_out);

Upvotes: 1

Views: 70

Answers (4)

j_mcnally
j_mcnally

Reputation: 6958

$("#data\\[User\\]\\[notify_one_day_out\\]").val(
               message.notify_one_day_out ? "1" : "0");

Upvotes: 0

Joseph
Joseph

Reputation: 119837

//this is actually a function call "$()" better reference it to avoid overhead
var el = $("#data\\[User\\]\\[notify_one_day_out\\]");

el.val( message.notify_one_day_out ? '1' : '0');

i suggest you turn those [] into dashes or underscores. that way it won't be that messy.

Upvotes: 5

Michael Mior
Michael Mior

Reputation: 28752

You can use the ternary operator.

$("#data\\[User\\]\\[notify_one_day_out\\]").val(message.notify_one_day_out ? "1" : "0");

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382666

You can use ternary operator (also called conditional operator):

$("#data\\[User\\]\\[notify_one_day_out\\]").val(
         message.notify_one_day_out ? '1' : '0' );

Here is prototype of ternary operator:

(expression) ? this if true : this if false;

Essentially it is shorthand of if-else statements.


You can read more about it here:

Upvotes: 0

Related Questions