Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JS if (condition) means == true or === true

Tags:

javascript

css

I know the difference between == and === however I always believed that if (condition) condition was supposed to be evaluated against true using strict equality (===) and not type-coercing equality (==).

See an example:

if (1) {
    console.log("1");
}

if (1 == true) {
    console.log("2");
}

if (1 === true) {
    console.log("3");
}

It returns:

::1
::2

I know 1 is not strictly equal to true, because the type is different, but when I do if (condition) according to W3C it should be the strict equality test (===) that is run not the type-coercing equality of ==.

So why is it logging 1?

like image 580
amandanovaes Avatar asked Nov 28 '22 14:11

amandanovaes


1 Answers

The if statement uses condition == true. It's given in the ECMAScript Language Specification, here: http://www.ecma-international.org/ecma-262/5.1/#sec-12.5

Note the usage of the ToBoolean() in Step 2. This converts the given argument to a Boolean value, meaning that yes, type coercion does occur for the condition of an if statement.

like image 191
Serlite Avatar answered Dec 09 '22 19:12

Serlite