Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is Variable Initialization statement an expression in JavaScript?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading