Difference between == and === in JavaScript
In this tutorial, we are going to see the difference between =, == and === in javascript.
- = is used to assign values to a variable in JavaScript.
- == is used for the comparison between two variables regardless of the type of the variable.
- === is used for a strict comparison between two variables i.e. it will check the type and value of both variables, which means it will check the type and compare the two values.
Let’s see some examples.
Example of the = operator
= operator is used to assign values to a variable in JavaScript.
var nbr = 15;
[st_adsense]
Example of the == operator
The ‘==’ operator tests for abstract equality, it performs the necessary type conversions before making the equality comparison.
// the string "15" is converted to integer 15 if (nbr == "15") alert("Both are equal"); else alert("Both are not equal");
Output:
Both are equal
[st_adsense]
Example of the === operator
The ‘===’ operator tests for strict equality, it will not do the type conversion, so if the two values are not of the same type, it will return “false”.
// No type conversion takes place if (nbr === "15") alert("Both are equal"); else alert("Both are not equal");
Output:
Both are not equal
Usually, the ‘===’ operator is recommended because it never does a type conversion, we are doing a strict comparison, so it always produces correct results.
[st_adsense]