null vs undefined
- Both are primitives
- Both are falsy:
- Boolean(undefined) //-> falseBoolean(null) //-> false
undefined
means that a variable has not been declared, or it has been declared but has not yet been assigned a value.null
is an assignment value that means “no value”. Javascript itself never sets a value tonull
- Difference in
typeof
:- typeof null; //-> "object"typeof undefined; //-> "undefined"
undefined
is not a valid JSON whilenull
is.
- Check if a variable is
null
:
variable === null;
- Check if a variable is
undefined
:
typeof variable === 'undefined';
// ⬇️ or this, but will throw ReferenceError if variable wasn't defined
variable === undefined;
- Comparison (Equality returns
true
and identity returnsfalse
) :
undefined == null; //-> true
undefined === null; //-> false
Last modified 2yr ago