What is difference between == and === in javascript
In this article, we will learn the difference between == and === in JavaScript.
Loose Equality Operator (==)
The double equal sign (==
) is known as the loose equality operator. This operator compares two values to see if they are the same after type coercion.
- If the values are equal (after conversion), it returns
true
. - If the values are not equal, it returns
false
.
Example 1:
console.log(11 == '11'); // Output: true
In this example, the output is true
because JavaScript converts the string '11'
to the number 11
before comparison.
Example 2:
console.log(12 == '11'); // Output: false
The result is false
because the values are different even after type coercion.
Strict Equality Operator (===)
The triple equals (===
) is called the strict equality operator. This operator compares both the value and the data type without coercion.
- Returns
true
only if the values and types are the same. - Returns
false
if the values or types differ.
Example 1:
console.log(11 === 11); // Output: true
The result is true
because both the value and type (number) are identical.
Example 2:
console.log(11 === '11'); // Output: false
The result is false
because the types differ (number vs. string), even though the values are the same.