javascriptif-statementconcatenation

Use of inline if/then/else in Javascript


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.


Solution

  • 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.

    console.log("<b>Test :</b> " + "null" == "null" ? "0" : "1" + "<br>")


    So you'll need to wrap the expression in quotes ()

    console.log("<b>Test :</b> " + ("null" == "null" ? "0" : "1") + "<br>")


    Or even better, use template literals (Backticks ` `) :

    console.log(`<b>Test :</b> ${"null" == "null" ? "0" : "1"}<br>`)