JavaTuto

JavaScript : Difference between == and ===

In this tutorial we will discover 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.

Example of the assignment operator =

var nombre = 25;

Exemple de l’opérateur de comparaison ==

The ‘==’ operator tests for abstract equality, it performs the necessary type conversions before making the equality comparison.

// string "15" is converted to integer 15
if (nombre == "15")  
   alert("Both are equal");    
else    
   alert("The two are not equal");

output :

Both are equal

Example of the comparison 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”.

// Aucune conversion de type n'a lieu
if (nombre === "15")  
   alert("Both are equal");    
else    
   alert("The two are not equal");

output :

The two are not equal

Usually the ‘===’ operator is recommended because it never does a type conversion, we do an exact comparison, so it always produces correct results.

Read more about JavaScript operators

Exit mobile version