DEV Community

Cover image for JavaScript undefined and null: Let's talk about it one last time!
Tapas Adhikary
Tapas Adhikary

Posted on • Updated on • Originally published at blog.greenroots.info

JavaScript undefined and null: Let's talk about it one last time!

In JavaScript, undefined and null are very different from each other. However, there are only a few similarities that may confuse a beginner to the language. This article aims to explain the similarities, differences, and usages with examples. Hope you find it useful.

What is undefined?

undefined typically means a variable has been declared but has not yet been assigned a value.

let author;
console.log(author); // prints, undefined
Enter fullscreen mode Exit fullscreen mode

In the above example, we have declared a variable author but haven't assigned a value to it. Hence the variable author is undefined.

There is also a way to confirm it,

typeof(author); // prints "undefined"
Enter fullscreen mode Exit fullscreen mode

When you access non-existent object properties, you get an undefined.

let article = {'title': 'How to do something..'};

console.log(article.title); // prints, "How to do something.."
console.log(article.author); // prints, undefined
Enter fullscreen mode Exit fullscreen mode

Watch out for: ReferenceError

In the case of undefined, the variable must be declared. On the contrary, accessing a variable that's not been declared will cause a ReferenceError.

console.log(rating);
Enter fullscreen mode Exit fullscreen mode

If you haven't declared the rating variable and trying to access it like shown above, you will get an error,

image.png

⚠️ Confusion Alert: Please do not be confused with the phrase, is not defined in the above error message. As explained, it doesn't mean undefined.

What is null?

null is an assignment value. You as a programmer may want to assign the value null to a variable. It simply means the value is blank or non-existent.

let author = null;
console.log(null); // prints, null
Enter fullscreen mode Exit fullscreen mode

Interestingly, when we use typeof to check the type of null, it returns "object".

typeof(null); // prints, "object"
Enter fullscreen mode Exit fullscreen mode

⚠️ Confusion Alert: This can be confusing as null is a primitive value. This is probably one issue JavaScript is living with for a long now and we expect better reasoning for it.

Similarities

There are a couple of similarities between undefined and null.

  • They both are primitive values. JavaScript has 7 primitive values,
    1. Number
    2. String
    3. Symbol
    4. Boolean
    5. BigInt
    6. undefined
    7. null.

All other values in JavaScript are objects(yes, including functions and arrays).

  • They both are falsey values.

A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context.

In JavaScript, there are 6 falsy values including undefined and null,

  1. false
  2. 0
  3. ""(empty string)
  4. NaN
  5. undefined
  6. null

Differences

Apart from the similarities mentioned above, undefined and null are way apart from each other. They are strictly not equal,

(undefined === null) // returns, false
(undefined !== null) // returns true
Enter fullscreen mode Exit fullscreen mode

⚠️ Confusion Alert: However, they are loosely equal. Loose equality is performed using the == operator which compares two values after converting them to a common type. You should try avoiding it.

(undefined == null) // returns, true
Enter fullscreen mode Exit fullscreen mode

Just remember, undefined means no value assigned for a declared variable. Whereas, null itself is a value that can be assigned to a variable, and null signifies an empty/blank value.

How to check for undefined and null?

Use the strict equality operator(===) to check if a variable is undefined or has a null value

let author ;

if (author === undefined) {
 console.log(`author is undefined`);
} else {
 // Do something
}
Enter fullscreen mode Exit fullscreen mode

Similarly, for null,

let author = null ;

if (author === null) {
 console.log(`The value of author is null`);
} else {
 // Do something
}
Enter fullscreen mode Exit fullscreen mode

As both undefined and null are falsy values, you can do this as well. It will match both undefined and null.

if (!author) {
 // Do something
}
Enter fullscreen mode Exit fullscreen mode

Usage Cheatsheet: undefined and null

With the understanding, we have so far, here is the cheat-sheet for using undefined and null,

// Declared age but not assigned any value to it
let age;

// Right way to check
age === null;  // returns, false
age === undefined;  // returns, true

// Don't use this 
age == null;  // returns, true            
age == undefined;  // returns, true



// Declared name and assigned a null value
let name = null;

// Right way to check
name === null;  // returns, true      
name === undefined;  // returns, false   

// Don't use this 
name == null;  // returns, true
name == undefined;  // returns, true       

// type checking
typeof  age;  // 'undefined'
typeof name;  // 'object'

// Create an object with one property where key is x and value is null
let obj = {x: null};

obj.x === null;   // true
obj.x === undefined;   // false
obj.y === null;  // false
obj.y === undefined;  // true


// Not possible
null = 'abcd';
// Possible, but don't do it
undefined = 'abcd';

Enter fullscreen mode Exit fullscreen mode

In Summary

To summarize,

  • undefined and null are primitive values and they represent falsy values. All the similarities between undefined and null end here.
  • undefined value is typically set by the JavaScript engine when a variable is declared but not assigned with any values.
  • null value is typically set by programmers when they want to assign an empty/blank value.
  • undefined and null are strictly not equal(!==).
  • If you try to access the value of a variable that is not even declared, it will result in a ReferenceError.

Before we end...

Thank you for reading this far! You can @ me on Twitter (@tapasadhikary) with comments, or feel free to follow.

If it was useful to you, please Like/Share so that, it reaches others as well. You may also like,

That's all for now. See you again with my next article soon. Until then, please take good care of yourself.

Top comments (10)

Collapse
 
oliverradini profile image
OliverRadini

Just out of interest, has anyone had this kind of thing affect them in any actual work? It seems to come up in interview questions etc. but I've never had it cause any kind of problem.

Collapse
 
atapas profile image
Tapas Adhikary

One way I think I have faced it..

Whenever I have written something like,

if (!age) {

}
Enter fullscreen mode Exit fullscreen mode

I was sure, it ruled out undefined and null too. Knowing it gives additional confidence, :)!

Collapse
 
hermannp profile image
hermann-p

To be exact, it will also rule out NaN, "", '', and -- very error prone -- 0.

Thread Thread
 
atapas profile image
Tapas Adhikary

Yeah true.. all those unwanted things! :)

Collapse
 
danytulumidis profile image
Dany Tulumidis

Nice read and a good refresher for me on this topic!

Collapse
 
atapas profile image
Tapas Adhikary

Thank you, Dany! Glad you liked it.

Collapse
 
myleftshoe profile image
myleftshoe • Edited

Thanks for the post!
minor typo: "converting them to a common time" - you probably meant type

also: "null itself is a value that can be assigned to a variable" - undefined can be too

Collapse
 
atapas profile image
Tapas Adhikary • Edited

Corrected the typo. Thank you!

Collapse
 
pengeszikra profile image
Peter Vivo

Nice to know about Symbol is primitive values!

Collapse
 
atapas profile image
Tapas Adhikary

Yeah, here is a good resource to know more about primitives,
developer.mozilla.org/en-US/docs/G...