In JavaScript, null
and undefined
are both special values that represent the absence of a meaningful value.
However, there are some key differences between them:
-
undefined
is a value that a variable can have if it has been declared but has not been assigned a value. It is also the default return value for a function that does not return anything.For example:
let x; // x is undefined function myFunction() {} // myFunction returns undefined
-
null
, on the other hand, is a value that represents the intentional absence of any object value. It is often used to indicate that a variable or property should have no value.For example:
let y = null; // y has no value let obj = { prop: null }; // obj.prop has no value
-
Another difference is that
undefined
is a primitive value, whereasnull
is an object. This means thatnull
is actually a special case of object, whereasundefined
is its own primitive type. -
Finally, it is important to note that
undefined
andnull
are both falsy values in JavaScript, meaning that they will be coerced tofalse
in a boolean context.For example:
if (!undefined) { console.log("dont print"); } if (!null) { console.log("dont print this one also"); }
Thank you for reading, and let’s have conversation with each other
Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.