techStackGuru

JavaScript Optional Chaining


The JavaScript chaining option allows safe navigation through nested object properties, preventing errors when accessing properties or methods with potentially undefined or null values.

Preventing Errors: It prevents errors from occurring when calling methods or accessing properties on undefined or null values. The execution of a program would be interrupted if an attempt was made to access a non-existent property or call a method on a non-existent method without optional chaining.

Example: Without Optional Chaining

const user = {
name: 'Vishal',
    address: {
        city: 'New York',
        postalCode: '10001'
    }
};

const city = user.address.city.toLowerCase(); 

console.log("City:", city); 


/* Output
City: new york */

Now lets comment the city and check

//city commented
const user = {
    name: 'Vishal',
    address: {
    //  city: 'New York',
      postalCode: '10001'
    }
};
  
const city = user.address.city.toLowerCase(); 
  
console.log("City:", city); 
  
/* Output
  ERROR!
/tmp/R5XO3uGBCU.js:11
const city = user.address.city.toLowerCase(); 
                               ^

TypeError: Cannot read properties of undefined (reading 'toLowerCase') */

Example: Lets use Optional Chaining

const user = {
    name: 'Vishal',
    address: {
      city: 'New York',
      postalCode: '10001'
    }
};
  
// Using optional chaining to access properties
const city = user.address?.city?.toLowerCase(); 

console.log("City:", city);

/* Output
City: new york */

Now lets comment the city and check again

const user = {
    name: 'Vishal',
    address: {
    //  city: 'New York',
      postalCode: '10001'
    }
};
  
// Using optional chaining to access properties
const city = user.address?.city?.toLowerCase(); 

console.log("City:", city); 

/* Output
City: undefined */

As shown above, in the event that city doesn't exist, it will return undefined, preventing TypeErrors from being thrown when toLowerCase() is called on an empty string.