JavaScript explanation = difference between == and ===

Jake Metz
Technical blog by JakeMetzDev
3 min readMay 27, 2018

= (The equals operator)

The equals operator is used for assignment. Using one = allows you to assign a value to something.

We first calculate the value on the right-hand side of the = and then put it into the variable that we declared on the left-hand side. Here, we assign the 1 value to the a variable. Then, we get the value of a ( which is 1), add 2 to it, then store that in the b variable.

== (The “loose equality comparison” operator)

The == checks for value equality with type coercion allowed. So, what is type coercion anyway? Defining this will go a long way in understanding the difference between == and === and in fact this is the key difference between the two.

TYPE COERCION:

Much like a human turns into a werewolf or a vampire turns into a bat type coercion is the process of converting value from one type to another (string to a number, object to boolean, etc).

In the a == b comparison, JavaScript notices that the types do not match (one a string and another a number), so it goes through the process of type coercion until both types match, where then the value equality comparison can be checked.

Moreover, in this case the the types are converted to numbers ( 2 and 2). This is important to note because one would think they also could have been strings (“2” and “2”). This doesn’t matter in our simple example but do be aware of this in more complex cases where it matters not just what the end result is but how you get there. For further reading on type coercion specifics check this out .

=== (The “strict equality comparison” operator)

The === checks for value equality without allowing coercion. Often the === is called ‘strict equality’ due to this reason.

The a === b produces false, because the type coercion is not allowed.

Why is this even important anyway?

In most cases it is best to avoid using the loose equality comparison operator. In my opinion it is a good idea to set the standard of using the strict equality comparison operator, then as your skills and understanding grow move towards using both when appropriate.

I’ve skilled up in my type coercion game, when should I use == versus ===?

To quote Kyle Simpson’s You Don’t Know JS series here are simple rules to when you should and shouldn’t use == and ===:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you’re safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

--

--