Home > database >  Is Variable Initialization statement an expression in JavaScript?
Is Variable Initialization statement an expression in JavaScript?

Time:02-01

The following works:

let x = 1 && console.log("true");  (-- logs true)
let y = 0 && console.log("true");  (-- logs nothing)

The above shows that the statement before && operator is acting like an expression.

Then I tried this:

console.log(let m = 5);  // Error

What is going on here? If that's an expression then why it didn't work in this case and if it's not an expression then why it worked in the first two cases?

CodePudding user response:

The following works -

let x = 1 && console.log("true");  (-- logs true)
let y = 0 && console.log("true");  (-- logs nothing)

The above shows that the statement before && operator is acting like an expression

This is where you are mistaken. The && operator is used to join expressions, not statements (even though it has control flow effects). This parses as follows:

let x = (1 && console.log("true"));  (-- logs true)
let y = (0 && console.log("true"));  (-- logs nothing)

console.log is acting as an expression here, not let .... Function calls always return a value (which may be undefined). If you logged x and y, you'd see that x === undefined (result of 1 && undefined) and y === 0 (result of 0 && <not evaluated>).

It is probably confusing you here that && short-circuits: In the first expression, the first operand of && is 1 (truthy), so the second operand - the expression which is a call to console.log - has to be evaluated; in the second expression, the first operand of && is the falsy 0, so && short-circuits to 0, not evaluating (not calling) console.log("true").

let statements are statements and not expressions, which is why you get a syntax error in your second example.

  • Related