Difference between == and === with Examples in JavaScript

difference between == and === in javascript

JavaScript has different types of operators. == and === in JavaScript are also operators.

== operator:

== operator is the equality operator. It checks whether the two values that are being compared are equal.

Example:

console.log(5 == 5);

Output:

true

== operator does not check whether the two values that are being compared are of the same datatypes. In cases like this javascript converts type of variable to value.

Example:

console.log(5 == “5”);

Output:

true

Explanation: As in above example both values(operands) are of different datatypes, javascript converts type of the second operand from string to a number.
So, the expression finally becomes 5 == 5 and that is true.

=== operator:

== operator is a strict equality operator. It checks whether the two values that are being compared are equal and whether their datatypes are equal. If both conditions are true then only === operator returns comparison result to true otherwise false.

Example:

console.log(5 === 5);

Output:

true

Explanation: As both values are equal and datatypes of both values are same the === operator gives results as true.

Example:

console.log(5 === “5”);

Output:

false

Explanation: As datatypes of both values are not the same the === operator gives results as false.

**Note:

Comparing data of different types may give an unexpected result. So, the use of === operator for comparison is recommended. But you can also use == operator if it is required for a specific task.

If you have any questions regarding == and === in javascript, please ask them through comments.

Leave a Reply

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