In JavaScript, there are two comparison operators used to check equality: ==
and ===
. While both operators are used for comparison, there is a difference between them.
The ==
operator checks for equality of values, but performs type coercion if the operands have different types. In other words, it converts the operands to a common type before comparing. For example, 1 == '1'
is true, since the string '1'
is converted to the number 1
before comparison.
On the other hand, the ===
operator checks for equality of values and type. It only returns true if the operands are of the same type and have the same value. For example, 1 === '1'
is false, since the operands have different types.
Here are some examples that illustrate the difference between ==
and ===
:
javascriptconsole.log(1 == '1'); // true
console.log(1 === '1'); // false
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(false == 0); // true
console.log(false === 0); // false
console.log(true == 1); // true
console.log(true === 1); // false
In the first example, 1 == '1'
returns true because the ==
operator performs type coercion and converts the string '1'
to the number 1
before comparison. However, 1 === '1'
returns false because the ===
operator does not perform type coercion and the operands have different types.
In the second example, null == undefined
returns true because both null
and undefined
are considered equal values by the ==
operator. However, null === undefined
returns false because the operands have different types.
In the third example, false == 0
returns true because the ==
operator converts false
to 0
before comparison. However, false === 0
returns false because the operands have different types.
In the fourth example, true == 1
returns true because the ==
operator converts true
to 1
before comparison. However, true === 1
returns false because the operands have different types.
Comments
Post a Comment