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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more