What is the difference between null and undefined in JavaScript?
Let’s talk about the similarities first.
null
and undefined
are JavaScript primitive types.
The meaning of undefined
is to say that a variable has declared, but it has no value assigned.
let age //age is undefined
let age = null //age is null
Note: accessing a variable that’s not been declared will raise a
ReferenceError: <variable> is not defined
error, but this does not mean it’sundefined
.
How do you check if a variable is null? Use the comparison operator, for example age === null
Same for undefined: age === undefined
In both cases, you can check for:
if (!age) {
}
and this will be matching both null
and undefined
.
You can also use the typeof
operator:
let age
typeof age //'undefined'
although null
is evaluated as an object, even though it is a primitive type:
let age = null
typeof age //'object'
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X