
optional chaining
(?.
) operator in JavaScript.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.let user = { name: 'Anvarbek', address: { city: 'Toshkent', street: 'Navoiy ko‘chasi' } };
city
field in the user
object, it's simple:console.log(user.address.city); // Toshkent
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


if
statements:if (user.address && user.address.city) { console.log(user.address.city); }
optional chaining
operator comes to the rescue:console.log(user.address?.city); // undefined (No error occurs)
user.address
does not exist, the value of user.address?.city
will be undefined
and the code will continue.- When accessing object fields:
let user = {}; console.log(user.profile?.age); // undefined
- When accessing array elements:
let users = null; console.log(users?.[0]); // undefined
- When calling functions:
let user = { sayHello: function() { return "Salom!"; } }; console.log(user.sayHello?.()); // Hello! console.log(user.sayGoodbye?.()); // undefined, no error
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.Similar Articles
Main features of Reactjs
In this article, we will learn about the key features of React.js, which will also be useful for interview questions.
August 21, 2024Destructuring assignment in JavaScript
In today's article, we will explore in detail another important JavaScript syntax: Destructuring assignment.
August 17, 2024First Class Function in JavaScript
Hello friends. In today's post, we'll go into detail about another important concept in JavaScript that plays a crucial role First Class Functions!
August 14, 2024What is React js? What role does React play in software development?
Today, we'll discuss React.js, one of the top JavaScript libraries, including its advantages, what we can do with it, and everything else you need to know in this post.
August 20, 2024What is an SPA (Single Page Application)?
Let's explore what an SPA (Single Page Application) is, which is used in today's modern websites.
August 29, 2024What is the DOM? What is the difference between HTML and the DOM?
In today’s post, we’ll discuss what the DOM (Document Object Model) is and the differences between HTML and the DOM.
August 31, 2024