DEV Community

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

Posted on

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)

Top comments (0)