Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simplify this jquery/javascript

I'm trying to improve my jquery/javascript syntax. Is there a better way to write this?

if (ok)
    var mymsg   = '<p id="ok-box">'
                +   "You're good to go"
                + '</p>';
}else {
    var mymsg   = '<p id="not-ok-box">'
                +   "Error"
                + '</p>';
}

I was thinking if jquery/javascript had a similar syntax to the following PHP syntax, it would be great:

$mymsg = ($ok) ? "You're good to go" : "Error";
like image 532
Chris Avatar asked Dec 14 '22 01:12

Chris


2 Answers

You mean like:

var mymsg = ok ? '<p id="ok-box">You\'re good to go</p>' :
    '<p id="not-ok-box">Error</p>';

It does! :)

like image 65
Anthony Mills Avatar answered Dec 25 '22 04:12

Anthony Mills


The best way to write that in my view is:

if (ok)
  var mymsg = '<p id="ok-box">You\'re good to go</p>';
} else {
  var mymsg = '<p id="not-ok-box">Error</p>';
}

Ternary operators make the code more confusing, not less. The most obvious change I can see is to get rid of superfluous string appending, and do it all in one go. The strings you've got are very straightforward, and don't really need to be broken up into 3 lines each.

like image 31
Dominic Rodger Avatar answered Dec 25 '22 04:12

Dominic Rodger