How is null equal to undefined and not equal to undefined within the same operator.
undefined == null
true
undefined !== null
true
undefined === null
false
undefined != null
false
How is null equal to undefined and not equal to undefined within the same operator.
undefined == null
true
undefined !== null
true
undefined === null
false
undefined != null
false
Undefined and null are empty variables. But to understand whats above you have to understand comparison operators. == is a comparison operator that can convert. === really tests if its the same without doing type conversion. So null is practically the same as undefined. Its a bit hard to understand when you first think about it but its really not that hard. Some examples:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
== converts the variable values to the same type before performing the actual comparison(making type coercion)
=== doesn't do type coercion and returns true only if both values and types are identical for the two variables being compared.
Let's take a look at some examples:
console.log(5 == "5"); // no type coercion is being made - hence, the result is true.
console.log(5 === "5"); // type coercion is being made, value is the same but the data types are not (number vs string);
console.log(undefined == null); // should be true because type coercion is not being made and the data values are both falsy!
console.log(undefined !== null); // should be true cause type coercion is being made and the data types are differnt!
console.log(undefined === null); // // should be false cause type coercion is being made and the data types are differnt.
console.log(undefined != null); // should be false cause type coercion is not being made and the data values are both falsy!
Please find my answer below.
"==" coerces the type of the variable before making a comparison. i. so undefined == null is true since both the variables coerces to false (since they both indicate an empty value) and post that comparison is made making them equal.
!== makes a strict comparison so the type is not changed, in case of undefined the type is "undefined" and in case of null the type is "object" which can be verified using typeof.
ii. so since the type does not match,!== return true i.e. undefined !== null.
iii. Same way === makes a strict comparison, so undefined === null is false, since the type is only different
iv. Lastly undefined != null is false, since != like == coerces the type of the variables to false, and then compares. Hence they both seem equal to != and it return false.