cover
JavaScriptOptional ChainingJavascript interviewInterviewJavaScript operator

Optional Chaining in JavaScript?

Summary
Today's topic will be about the Optional Chaining (?.) operator that appears in top Javascript interview questions. Optinal Chaining is used in many places and is considered one of the most necessary operators. Let's start with what it is!
Category
JavaScript
Optional Chaining
Javascript interview
Interview
JavaScript operator
Cover
https://ghalex.com/wp-content/uploads/2019/12/Frame-2-1.jpg
Slug
javascripda-optional-chaining
Date
author
Published
Published
Hello, friends, today we will discuss in detail about optional chaining (?.) operator in JavaScript.
Optional chaining is considered a much safer and better way to access and retrieve the value of an Object Property.
Well, let's dig deeper into what's going on!!! In general, it makes it easier to work with non-existent (undefined) values when accessing object and array elements. This operator is used to simplify the code and return undefined instead of value if no value exists.
Example:
Suppose we have the following object:
let user = { name: 'Anvarbek', address: { city: 'Toshkent', street: 'Navoiy ko‘chasi' } };
If you want to get the city field in the user object, it's simple:
console.log(user.address.city); // Toshkent
But if user.address doesn't exist, this code throws an error:
let user = { name: 'Anvar' }; console.log(user.address.city); // TypeError: Cannot read property 'city' of undefined
notion image
notion image
 
To avoid such errors, it is usually necessary to use if statements:
if (user.address && user.address.city) { console.log(user.address.city); }
But it can be inconvenient and long for many people in many places. It is in such situations that the optional chaining operator comes to the rescue:
console.log(user.address?.city); // undefined (No error occurs)
In the above example, if user.address does not exist, the value of user.address?.city will be undefined and the code will continue.
Main areas of application:
  1. When accessing object fields:
let user = {}; console.log(user.profile?.age); // undefined
  1. When accessing array elements:
let users = null; console.log(users?.[0]); // undefined
  1. When calling functions:
let user = { sayHello: function() { return "Salom!"; } }; console.log(user.sayHello?.()); // Hello! console.log(user.sayGoodbye?.()); // undefined, no error
Final result:
Optional chaining makes code cleaner and safer to write. With this operator, you can automate checking for undefined or null values without having to rewrite the code in many places.
Back

Similar Articles

Anvarbek Dev © 2024 All rights reserved.