How does the single equal sign work in the if statement in javascript

The first part of your analysis is of course correct.

Now, the interesting part might be why your last code if (var ...) { doesn’t work.

It doesn’t work because

1)

var something

is a statement, not an expression.

2) here’s how ECMAScript defines the if statement :

IfStatement :

if ( Expression ) Statement else Statement

if ( Expression ) Statement

You must put an expression in the if clause, not a statement.

More on expressions vs statement in this article.

Leave a Comment