What’s the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both primitive values.

An undefined variable is a variable that has been declared but doesn’t have a value assigned (yet).

For example, try logging the following variable:

let dogBreed 
// undefined

You get undefined because the dogBreed variable has no value.

null is a value that is commonly assigned to a variable. For example, to avoid having an undesired undefined variable in your code, you can assign the value null to that variable (and give it a real value later):

let dogBreed = null
// null

Bonus info:

null is evaluated as an object, which the following code shows:

console.log(typeof dogBreed) 
// object

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on