In JavaScript, null
and undefined
are both falsy values, but they represent different things. So what is the difference?
The intentional absence of a value
The null
value represents the intentional absence of any object value.
For example, if you try to use the querySelector()
method to get an element that doesn't exist, the method will return null
:
const nonExistent = document.querySelector('#non-existent'); // null
In the example above, I try to get the element with the ID #non-existent
, but there is no such element, so the querySelector()
method returns null
.
The element doesn't exist in an undefined
state. It doesn't exist at all, so it's just null
. The querySelector()
method says "hey, there's no such thing, so I'm returning null
to explicitly tell you that."
Variables with no value
The undefined
value is automatically assigned to variables that have just been declared, or to formal arguments for which there are no actual arguments.
For example, if I create a variable without assigning it a value, it becomes undefined
:
let myName; // undefined
In the example above, the myName
variable does exist, but it doesn't have a value, so it becomes undefined
.
Similarly, if a function is expecting an argument but I don't provide one, its value becomes undefined
:
function sayHello (name) {
console.log(`Hello, ${name}!`);
}
sayHello(); // Hello, undefined!
In the example above, the name
parameter does exist, but I don't pass in a value for it, so it becomes undefined
instead.