skip to Main Content

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


  1. 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>`)
    Login or Signup to reply.
  2. 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.

    let result = null == null ? 0 : 1;
    console.log("<b>Test:</b> " + result + "<br>")
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search