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";
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! :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With