Undefined vs Null in JavaScript

Francesco Ciulla - Mar 28 '20 - - Dev Community

Maybe you don't need to read all the article, i just can show you this:

Alt Text

undefined

undefined is a property of the global object.

It is a primitive value: undefined.

It is treated as falsy in boolean expressions.

undefined can be:

  • the type of a variable that has not been assigned yet.
  • the return value of a method or statement if the evaluated variable does not have an assigned value.
  • the return value of a function, if no value was returned.

You can also explicitly set a variable to undefined: (don't do it)

const a = undefined; //accepted, but can lead to confusion!
Enter fullscreen mode Exit fullscreen mode

null

null is an intentional absence of any object value.

It is a primitive value: null.

It is treated as falsy for boolean operations.

The value null is written with a literal: null.

null is not an identifier for a property of the global object.

Null expresses a lack of identification, indicating that a variable points to no object.

For Example, In many API, null is often retrieved in a place where an object can be expected but no object is relevant.

  • null is an empty or non-existent value.
  • null must be assigned.

Also, undefined and null are two distinct types:

Unassigned variables are initialized by JavaScript with a default value of undefined.

JavaScript never sets a value to null, that must be done by the developer.

What do we get if we compare null and undefined with '==' and '===' operators?

console.log(null == undefined); // true
console.log(null === undefined); // false
console.log(typeof null); // "object" (not "null" for legacy reasons)
console.log(typeof undefined); // "undefined"
Enter fullscreen mode Exit fullscreen mode

Arithmetic Operations

Another difference is when we try to perform the arithmetic operation +

  • with null results as an integer
  • with undefined results is NaN
console.log(3 + null); //3
console.log(3 + undefined); //NaN
Enter fullscreen mode Exit fullscreen mode

in Conclusion

undefined typically means a variable has been declared, but not defined.

null is an assigned value, It means no value on purpose.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .