console.log(1 == 1) //true
Equality vs Strict Equality
Equality ==
- Compares values for equality if types of values are same. For example
- If type of values are different then values is first converted and than compared. Javascript tries to convert the operand to the same type before comparision.
console.log('1' == 1) //true
In the above case value '1' is converted to number and than compared, even '1' is of string type and 1 is of number comparison between two return true.
- For Objects and Array there reference is checked if they are same, there values are not compared.
const obj1 = { value: "1" }; const obj2 = { value: "1" }; console.log(obj1 == obj2); //false const names1 = ["bippan"]; const names2 = ["bippan"]; console.log(names1 == names2); //false
Strict Equality ===
- Strict Equality checks types and does not convert the operand if types are different. If types are different it returns false.
console.log(3 === '3'); // false
console.log('true' === true); // false
console.log(null === undefined); // false
console.log(0 === false); // false
console.log('' === 0); // false
If types are same than values is compared.
console.log(3 === 3); // true
console.log('hello' === 'hello'); // true
console.log(true === true); // true
console.log(null === null); // true
console.log(undefined === undefined); // true
In case of Arrays and Objects reference is compared
const obj1 = { name: 'Bippan' };
const obj2 = { name: 'Bippan' };
const obj3 = obj1;
console.log(obj1 === obj2); // false
console.log(obj1 === obj3); // true
In the above case obj1 and obj2 share the same reference true is returned.
Same comparison happens for arrays.
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
const arr3 = arr1;
console.log(arr1 === arr2); // false
console.log(arr1 === arr3); // true
Some Exceptions which are important to note
- Comparison between NaN with anything, including itself, using equality operators will always return false. This is because NaN is considered not equal to any value, even itself.
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
- Comparing Null and Undefined will be equal with equality comparison, all other comparison between these two returns false.
console.log(null == undefined); // true console.log(null === undefined) // false
- Empty String is equal to false in equality comparison.
console.log("" == false); // true
- When comparing Arrays and Objects always remember that they are compared by reference and not by their values.
const obj1 = { name: 'Bippan' }; const obj2 = { name: 'Bippan' }; console.log(obj1 === obj2); // false const arr1 = [1, 2, 3]; const arr2 = [1, 2, 3]; console.log(arr1 === arr2); // false