JavaScript – Difference Between =, ==, and === Operators

assignment-operatorequalityjavascriptoperators

I have written some code and in certain places == is required and in others = is required. Can someone explain the differences or point me in the direction of the resource that can?

Example:

if($("#block").css.display == "none"){
  $("#block").css.display = "block";
}

The only thing I can come up with is that in one I’m changing and in the other I’m checking. But in both I am referring to equality.

Best Answer

= is the assignment operator. It sets a variable (the left-hand side) to a value (the right-hand side). The result is the value on the right-hand side.

== is the comparison operator. It will only return true if both values are equivalent after coercing their types to the same type.

=== is a more strict comparison operator often called the identity operator. It will only return true if both the type and value of the operands are the same.

I would check out CodeCademy for a quick intro to JavaScript.

If you prefer to read more, MDN is a great intro as well.

For those concerned about the source of the term "identity operator" jbabey pointed out that JavaScript: The Definitive Guide seems to mention it.

Related Question