JavaScript null vs undefined

JavaScript null vs undefined

  1. null in JavaScript
  2. undefined in JavaScript
  3. Why Do People Confuse null and undefined With Being the Same in JavaScript?
  4. Differences Between null and undefined in JavaScript

JavaScript is a powerful language, but using different data types can be confusing, especially for beginners. The null and undefined data types seem to represent nothing, but they’re different.

One needs to distinguish between these and know when to use which one to avoid runtime bugs.

This article discusses null and undefined and their difference.

null in JavaScript

null is an object in JavaScript. If it doesn’t make sense, that’s alright because it is a bug in JavaScript. It is supposed to be one of the primitive data types, but making this change will break many existing codebases.

It’s a user-assigned value; JavaScript never gives variables the value of null on its own. It’s a value assigned to variables that are left blank. It can be referred to as an empty value.

undefined in JavaScript

undefined is a state. When we declare a variable but never initialize it with a value, then it’s called undefined. It’s the default value used by JavaScript to initialize variables. It’s also an empty value.

Why Do People Confuse null and undefined With Being the Same in JavaScript?

null and undefined are the same in the following aspects:

  • Both are primitive data types.
  • If you compare them using the equality operator ==, it returns true.
null == undefined; // returns true	

JavaScript considers both as empty values.

  • undefined and null both yield false when used in an expression.

Differences Between null and undefined in JavaScript

  • Type Difference
console.log(typeof(null)); // object
console.log(typeof(undefined)); // undefined

In the example above, we use the typeof operator to check their data types. It returns the null data type as an object and the undefined data type as undefined. Although the equality operator == returns true, the identity operator === will return false since they are equal in value but have a different data type.

  • Arithmetic Operations

null behaves like a number with no value when performing arithmetic operations. Performing operations give results similar to as if null were 0.

console.log(4+null); // 4
console.log(4*null); // 0
console.log(4-null); // 4
console.log(4/null); // Infinity

It’s important to note that although it may be treated as 0 in arithmetic operations, the value of null is not 0.

Meanwhile, undefined returns NaN when used in arithmetic operations.

console.log(4+undefined); // NaN
console.log(4*undefined); // NaN
console.log(4-undefined); // NaN
console.log(4/undefined); // NaN