DEV Community

Sojin Samuel
Sojin Samuel

Posted on

Null Vs Undefined in JavaScript [No More Doubts from 2022]

The existence of null and undefined in JavaScript may be misleading.

In order to help you decide whether to use null or undefined, lets make some few distinctions.

Undefined indicates that the property has not being defined yet. Null, on the other hand, indicates that a property has been specified but is empty.

I'm going to provide you an example that exemplifies the distinction in order to clarify the concept:

const person = {
    id: 1,
    name: "Harry",
    age: null
}

console.log(person.age); // null
console.log(person.birthday); // undefined
Enter fullscreen mode Exit fullscreen mode

In this case, null signifies that the age property has been specified but has not yet been assigned a value.

You can see this distinction when we try to log person.age and person.birthday. The birthday property has not been defined yet, which is why it returns undefined.

Due to this, we were forced to use the value null for age so that it would be obvious that the age property had been declared but had not yet been given a value.

This distinction would be nullified if age had been assigned the value undefined (which is conceivable).

But keep in mind that this differentiation is not frequently required.

Top comments (0)