Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ternary operator in nodejs

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.

like image 404
Hemadri Dasari Avatar asked Sep 05 '18 02:09

Hemadri Dasari


Video Answer


2 Answers

What 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 comma 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.)

like image 98
CertainPerformance Avatar answered Oct 22 '22 08:10

CertainPerformance


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"
like image 31
Anthony Avatar answered Oct 22 '22 08:10

Anthony