-1

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
  • 3
    That is called a ternary operator and yes, you can do what you want by rapping it in parenthesis like this: console.log("<b>Test :</b> " + ("null" == "null" ? "0" : "1") + "<br>") Commented Nov 11, 2024 at 17:11
  • 1
    btw, what is ; doing inside of the expression? Commented Nov 11, 2024 at 17:12

2 Answers 2

2

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>`)

Sign up to request clarification or add additional context in comments.

Comments

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>")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.