DEV Community

Yogini Bende
Yogini Bende

Posted on • Updated on

JS Basics: Difference between "null" and "undefined"

Hi Folks,

If you are working in javascript, you must be knowing these two keywords, null and undefined. Although we understand both of them, it becomes difficult to answer this particular question. So in today’s post let’s understand the difference between null and undefined.

Null and undefined are both falsy values and they are one of the javascript primitives ('string','number','null','undefined','boolean','symbol', 'bigint'). Now let's understand their difference.

The keyword undefined, as its verbal meaning says, is not defined. For example, If you are declaring a variable a and you are not passing any value to it. This means its value is not defined and so the variable a will get value undefined. Whenever you call a function or a variable and javascript do not know its value it will always return undefined. Try to do this, Declare a variable num and don't pass any value to it. Now let's print the variable num's value console.log(num) in your browser console and you will see undefined getting printed. This happened because your browser did not know the value of num as we had not defined it before! Also, as it is one of the javascript primitives, the type of undefined is also undefined!

We already have understood that, if something is not defined javascript gives it value is undefined. But then what about null? So null is something whose value you want to be nothing. Let me explain, suppose you have defined a variable a and you want its value to be nothing initially, So, instead of not giving it any value and making it undefined, you pass it Null meaning no value. Also, the type of null is an object. This is why according to MDN documentation, javascript has 6 primitives and there also is null, which is seemingly primitive, but indeed is a special case for every Object

So though null and undefined are almost the same, they have these differences in their types. While doing equality comparison in both, as both are falsy values == will give you a result true, but as both have different types, === will give you the result as false.

That’s all about Null and undefined.

Though this is a very basic topic, it becomes a tricky question for an interview! So share your comments/feedback about the article and also any of such tricky interview questions from your javascript interviews.

You can also connect with me on Twitter or buy me a coffee if you like my articles.

Keep learning :)

Top comments (1)

juancarlos_maciasnajera profile image
Juan carlos Macias najera

Thanks for the explanation is very helpful