More fun with ‘==’ and ‘===’

JavaScript does type coercion when doing comparisons

'0' == 0 evaluates to true

because the string gets coerced to a number.

Remembering our issues with ‘truthy’ and ‘falsy’ we may sometimes wish to use === which evaluates the expression based on both the value and the type of the two sides:

'0' === 0 evaluates to false

(because the items are different types)

Using our friend the unary operator can force the string into a number type before the comparison is made. So:

+'0' === 0 evaluates to true

Other fun expressions:

-1 == '-1' evaluates to true
-1 === '-1' evaluates to false
-1 === +'-1' evaluates to true
-1 === -'-1' evaluates to false
-1 === -'1'  evaluates to true
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s