Is it possible to use inline conditional statements in concatenation?
For instance,
console.log("<b>Test :</b> " + "null" == "null" ? "0" : "1"; + "<br>")
produces an error.
Is it possible to use inline conditional statements in concatenation?
For instance,
console.log("<b>Test :</b> " + "null" == "null" ? "0" : "1"; + "<br>")
produces an error.
2
Answers
Ternary operator don’t need to be closed with a
;
, remove that and it works fine, but gives the wrong output since it’s seeing the addition as the expression.So you’ll need to wrap the expression in quotes
()
Or even better, use template literals (Backticks
` `
) :This is an example of why attempts to optimize code before you actually have it working is a bad idea.
As others have stated, yes you can do this, but you can make this easier to read (and therefore avoid potential syntax errors), by splitting this up into two statements. Optimized code is not always the best code.