| by Gagandeep Singh | No comments

undefined and null in Javascript

undefined

In Javascript undefined (a primitive type in Javascript) gets assigned to a variable that we declare but don’t assign a value to. It’s Javascript’s way of telling that the value of this variable is not defined.

Even a function in Javascript which does not return anything, will return undefined by default.

So, to avoid any error we should never assign undefined to a variable manually.

typeof undefined

outputs: undefined


null

Unlike undefined, null (another primitive type in Javascript) is used when we want to manually or intentionally set the value of a variable to be empty.

When comparing null with undefined remember to use === instead of ==, reason being

null == undefined

returns true as it doesn’t check for the type and performs type-conversion

null === undefined

return false

typeof null

is object and not null (more details here)