devxlogo

undefined vs. null

undefined vs. null

Question:
 

Answer:
You are probably familiar with a special value in JavaScript called null. This is a value you can assign to a variable when you want to indicate that the variable has no particular value.

Well, kind-of. The fact is, null is a value, too — just like true, false, NaN, and Infinity.

Contrary to popular belief, unassigned variables (and object properties) do not begin with a default value of null. Instead, they begin with a special value called undefined.

Although it’s difficult to distinguish between undefined and null, the two values are, in fact, distinct, as demonstrated in the following scripts.

script 1

value = window . wiper;alert (“value is ” + value);

script 2

value = null;alert (“value is ” + value);

script 3

value = window . wiper;alert (value == null);

script 4

value = null;alert (value == null);

In Script 1, value equals undefined because window does not have a property named wiper. In Script 2, however, value is defined: It is defined as null. Script 3 demonstrates that when undefined is compared to null, the result is true. But null also equals null, as shown in Script 4.

So what does all this mean? Fortunately, not much: In most cases, there is little need to distinguish between null and undefined. However, if you have a habit of comparing variables to null just to see if they are defined, don’t forget that the results may be inconclusive. A true comparison means either that the variable is undefined or that the variable has been defined as null.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist