Equality

So far, you’ve seen how you can use==and!=to compare numbers and strings for equality. However, if you use==and!=in situations where the data you’re comparing is mixed, it can lead to some interesting results. For example,

"1" == 1

Returns:true

and

0 == false

Returns:true

JavaScript takes the string"1", converts it totrue, and compares it to the booleantrue.

"1" == true

Returns:true

When you use the==or!=operators, JavaScript first converts each value to the same type (if they’re not already the same type); this is why it's called "type coercion"! This is often not the behavior you want, andit’s actually considered bad practice to use the==and!=operators when comparing values for equality.

Strict equality

Instead, in JavaScript it’s better to usestrict equalityto see if numbers, strings, or booleans, etc. are identical in_type_and_value_without doing the type conversion first. To perform a strict comparison, simply add an additional equals sign=to the end of the==and!=operators.

"1" === 1

Returns:false

This returns false because the string"1"is not the same type_and_value as the number1.

0 === false

Returns:false

This returns false because the number0is not the same type_and_value as the booleanfalse.

results matching ""

    No results matching ""