undefined is a value representing a variable that has been declared but has not been assigned a value. On the other hand,
null is a value that represents that a variable has been given a value, but the value is empty. In other words,
undefined means that the variable is not defined, whereas
null implies that the variable is defined but has no value.
Checking for undefined variables
The simplest way to check for undefined variables is to use the
typeof operator. The
typeof operator returns the data type of a variable, and if the variable is undefined, it replaces “undefined”.
let x; console.log(typeof x); // outputs "undefined"
Checking for null variables
To check for null variables, we can use the equality operator
== or the strict equality operator
== operator compares two values for equality and returns
true if they are equal. On the other hand, the
=== operator compares two values for strict equality and returns
true if they are identical and of the same type.
let y = null; console.log(y == null); // outputs "true" console.log(y === null); // outputs "true"
Combining checks for undefined and null
It is often necessary to check for both undefined and null values simultaneously. To do this, we can use the
|| operator, which returns the first truthy value it encounters.
let z; console.log(z || "z is undefined or null"); // outputs "z is undefined or null" let a = null; console.log(a || "a is undefined or null"); // outputs "a is undefined or null"
typeof operator, equality operators, and the
|| operator, we can quickly check for these values in our code. This can help us to avoid errors and improve the overall quality of our code.
Thanks for reading. Happy coding!