JavaScript

Difference between == and === in JavaScript

In this tutorial, we are going to see the difference between =, == and === in javascript.

  1. = is used to assign values to a variable in JavaScript.
  2. == is used for the comparison between two variables regardless of the type of the variable.
  3. === 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;

 

 

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

 

 

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.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *