Computer >> Computer tutorials >  >> Programming >> Javascript

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

In JavaScript, null and undefined are both primitive values.

Read all about primitive vs. non-primitive value in JavaScript.

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
console.log(dogBreed)
// null

Bonus info:

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

console.log(typeof dogBreed) 
// object