Back to all questions

What is the difference between null and undefined in JavaScript?

Devs Hive

Devs Hive

Seen on interview: 4 users

The difference between null and undefined is a classic question for junior developer positions. At their core they are similar and both mean that there is no value, but if you dig a little deeper, the difference becomes obvious. Let's go through them one by one:

undefined

This type means that a value has not been assigned. In other words, it shows up when we declare a variable without assigning a value, access an object property that doesn't exist, or, more simply, call a function that doesn't explicitly return a value, since such a function always returns undefined.

null

It represents an empty value, and overall it is similar to undefined, with one important difference: null doesn't occur naturally in JS and can appear as a value only when a developer has explicitly set it.

For example, if no product is found in the database by ID, and you explicitly return null, you make it clear that you did look and found nothing, so you used null as the value.

function findProductById(id) {
const products = [{ id: 1, name: "Phone" }]; // емулюємо базу даних

const product = products.find(p => p.id === id);

return product || null;
}

Seen on interview?

Related Questions

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!