I am trying to do conditional check using ternary operator in nodejs.
The ternary operator is working fine without issues in below scenario. It prints text in console
{true ? (
console.log("I am true")
) : (
console.log("I am not true")
)}
And the same is not working under below scenario and it throws following error
let text = "I am true";
^^^^
SyntaxError: Unexpected identifier
{true ? (
let text = "I am true";
console.log(text);
) : (
console.log("I am not true")
)}
I am trying to do conditional check using ternary operator in nodejs.
The ternary operator is working fine without issues in below scenario. It prints text in console
{true ? (
console.log("I am true")
) : (
console.log("I am not true")
)}
And the same is not working under below scenario and it throws following error
let text = "I am true";
^^^^
SyntaxError: Unexpected identifier
{true ? (
let text = "I am true";
console.log(text);
) : (
console.log("I am not true")
)}
I am unable to understand why this is behaving differently.
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Sep 5, 2018 at 2:50 Hemadri DasariHemadri Dasari 34k40 gold badges124 silver badges165 bronze badges3 Answers
Reset to default 9What follows the ?
or the :
in the conditional (ternary) operator must be an expression, not statements. Expressions evaluate to a value. Variable assignment, like let text = "I am true";
, is a statement, not an expression - it does something (assigns "I am true" to the text
variable) rather than evaluating to some value.
You also can't have semicolons inside of parentheses, when those parentheses are expected to evaluate to an expression. If you really wanted to, you could use the ma operator instead, though it's a bit confusing:
let text;
(true ? (
text = "I am true",
console.log(text)
) : (
console.log("I am not true")
))
But the conditional operator still isn't appropriate for this situation - the conditional operator evaluates to a value (it's an expression in itself). If you aren't going to use the resulting value, you should use if/else
instead:
let text;
if (true) {
text = "I am true";
console.log(text);
} else console.log("I am not true");
The time to use the conditional operator is when you need to use the resulting value, for example:
const condition = true;
const text = condition ? 'I am true' : 'I am not true';
console.log(text);
(See how the result of the conditional operation is being used here - it's being assigned to the text
variable.)
You can't do assignment like that in a ternary operator. You would need to do something like:
let text = myCondition
? "I am true"
: "I am not true"
let text;
true ? (text = "I am true") : (text = "I am not true");
console.log(text);