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

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

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"

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

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);

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

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

typeof(null); // prints, "object"

⚠️ 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

⚠️ 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

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
}

Similarly, for null,

let author = null ;

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

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
}

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';

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. Please hit the Subscribe button at the top of the page to get an email notification on my latest posts.

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.

Did you find this article valuable?

Support Tapas Adhikary by becoming a sponsor. Any amount is appreciated!