I've been watching some videos from Tut+ about Js.They said that sometimes "undefined" is equal to "null". So, when does this happen ?
4 Answers
undefined == null
// => true
undefined === null
// => false
== tests for equality, === tests for identity (or strict equality). If in doubt, use ===.
7 Comments
Just to add on , This question is somehow answered already, check here
You can just check if the variable has a truthy value or not. That means
if( value ) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
Comments
this is because of the poor typing in JS
null === undefined // false
null == undefined // true
great!!!
good practice is not to use null at all in js. You cannot not get rid of undefined because it is built in. if you access an undefined variable its === undefinded, but not equals null, right? So to not get confused, just stop using it. define it as undefined, but not as null ;)
so don't use null
5 Comments
undefined and null. undefined is when you're accessing something that doesn't exists. But null is when you're accessing something that is null. One should be implicit while the other is an explicit value. You shouldn't set explicitly undefined to anything, instead you should always set it to null.In JavaScript, the == and === operators are used to compare values, but they behave differently:
console.log(null == undefined); // true
Reason: When using ==, JavaScript considers null and undefined to be equal because they are both treated as "empty" or "non-existent" values in this context. Essentially, == compares the values after converting them to a common type, and for null and undefined, they are considered equivalent.
=== Operator (Strict Equality)
- The
===operator is known as the strict equality operator. - It does not perform type conversion and compares both the value and the type.
console.log(null === undefined); // false
Reason: When using ===, JavaScript checks both the type and the value without converting either operand. Since null is of type object and undefined is of type undefined, they are not strictly equal, and the comparison returns false.