JavaScript has two distinct values for representing the absence of something: null
and undefined
. While they might seem similar, they serve different purposes and are used in different scenarios. Consider two boxes: one is empty (null), meaning someone intentionally removed its contents, and the other hasn’t been opened yet (undefined), meaning it’s still in its original, untouched state. Understanding the distinction can help you write cleaner and more predictable JavaScript code.
Let’s break down the concepts of null
and undefined
with examples:
What is undefined
?
In JavaScript, a variable is undefined
when it has been declared but has not been assigned any value. It is also the default return value for functions that don’t explicitly return anything.
Syntax and example of undefined