DEV Community

Cover image for Null vs Undefined in JavaScript
SYED MAZHAR ALI RAZA
SYED MAZHAR ALI RAZA

Posted on

1 1

Null vs Undefined in JavaScript

Do you really know the difference between "null" and "undefined" in JavaScript? If not, let me explain.

Undefined

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value. For example:

X is like a new team member in your company who hasn't been assigned any role yet.

let X;

console.log(X) 
undefined

console.log(typeof X)
undefined
Enter fullscreen mode Exit fullscreen mode

Null

Null is an assignment value. It can be intentionally assigned to a variable as a representation of no value: For example:

X is like a team member in your company who has been intentionally told to do nothing as of now.

let X = null;

console.log(X) 
null

console.log(typeof X) 
object
Enter fullscreen mode Exit fullscreen mode

typeof(null) will interestingly return 'object'. Unfortunately, this can be considered a bug in JS where the datatype of null is an object.]

Also, note that undefined == null will return true, meanwhile undefined === null will return false. It means null is equal to undefined but not identical(because they have different datatypes).

Happy coding :)

10daysofJSfundamentals (Day 2)

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay