JavaScript Optional Chaining “?”: How it Works with Examples

javascript optional chaining

JavaScript optional chaining lets you access object values without runtime errors. It checks if a property exists before access and prevents the code from breaking.

What is JavaScript Optional Chaining?

Optional chaining is a syntax in JavaScript. It uses ?. to access nested values safely. It checks if a value exists before access and stops if it does not.

Here is the syntax:

object?.property
object?.method()
object?.[expression]

So, how it works:

  • JavaScript checks the left side of ?..
  • If the value is null or undefined, it stops.
  • If the value exists, it continues and reads the property or calls the method.

Optional chaining saves time in null checks. It avoids long checks with &&. It makes code shorter and easier to follow.

Benefits and limitations.

  • It prevents errors from undefined or null values.
  • It makes code smaller and cleaner.
  • It only works in modern browsers and Node.js versions.

The Differences Between Optional Chaining “?” and Logical Operators

Logical operators like || and && handle truthy and falsy values. Optional chaining only checks if a value is null or undefined.

Here is a table showing you the key differences:

Stops at the first false or first trueLogical Operators (|| / &&)
PurposeAccess nested propertyHandle truthy or falsy values
Stop ruleStops at null or undefinedStops at first false or first true
Use caseObject property accessStops at the first false or first true

Optional chaining fits property access. Logical operators fit conditions. Both have different focuses on code flow.

Examples

Access nested object value:

let user = { profile: { name: "David Alaba" } };
let username = user?.profile?.name;
console.log(username);

This code checks if user and profile properties already exist before accessing them to avoid an error if one is missing, and still returns Ali when present.

Here is the output:

David Alaba

Call method:

let book = {
  getTitle: function() {
    return "JavaScript Tutorials by FlatCoding Team";
  }
};

console.log(book?.getTitle?.());

This code runs getTitle only if it exists and skips execution if the method is not there.

Here is the output:

JavaScript Tutorials by FlatCoding Team

Optional chaining with arrays:

let data = { items: ["one", "two", "three"] };
let first = data?.items?.[0];
console.log(first);

It checks for the items property before accessing it and avoids an error if items does not exist.

Here is the result:

one

Advanced case with function call in chain:

let api = {
  response: () => ({ code: 200, body: { message: "Okay" } })
};

let message = api?.response?.().body?.message;
console.log(message);

This code calls response if it exists, and then checks if body and message exists.

This will print the result below:

Okay

Wrapping Up

You learned what optional chaining is and how it works with syntax.

Here is a quick recap:

  • It uses ?. to stop at null or undefined.
  • It helps you to prevent errors in nested values.
  • Logical operators handle truthy or falsy checks instead.
  • Use it for property access and use logical operators for condition flow.

FAQs

What is JavaScript Optional Chaining?

JavaScript Optional Chaining helps access deep object properties safely without throwing errors.

const user = { profile: { name: "Alex" } };
console.log(user?.profile?.name); // Alex
console.log(user?.account?.id); // undefined

How do you use Optional Chaining with objects?

You can use ?. when accessing object properties.

const book = { details: { title: "JS Guide" } };
console.log(book?.details?.title); // JS Guide
console.log(book?.author?.name); // undefined

Can Optional Chaining be used with functions?

Yes, you can check if a function exists before calling it.

const tools = { log: () => "Run log" };
console.log(tools.log?.()); // Run log
console.log(tools.print?.()); // undefined

What are the benefits of Optional Chaining?

  • Prevents runtime errors
  • Makes code short and clear
  • Works with objects arrays and functions

Similar Reads

JavaScript with Function Guide: Syntax with Examples

JavaScript has a statement called "with" that changes how code accesses object properties. The"with" Function makes a temporary scope, so…

JavaScript Loops and Iteration: How They Work with Examples

You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…

Top 5 Code Editors: The Best IDE for JavaScript

If you are a coder, one of your primary requirements is to have a trustworthy code- editor. A Code editor…

Data Types in JavaScript: Primitive and Non-Primitive

Data types in JavaScript help hold values and shape code rules. They set clear plans for text, numbers, and other…

JavaScript Math sqrt: How to Find Square Root of a Number

JavaScript Math.sqrt() solves the need to get square roots fast. Before it, you wrote custom code or used loops. It…

JavaScript unshift Function: How it Works with Examples

The JavaScript unshift function adds one or more elements at the start of an array. It shifts existing items to…

JavaScript Garbage Collection: How it Works with Examples

JavaScript removes unused memory blocks with garbage collection. It frees memory space so programs run without leaks. What is JavaScript…

JavaScript Nullish Coalescing Operator Guide with Examples

The JavaScript nullish coalescing operator (??) gives a default value when a variable is null or undefined. Understand the Nullish…

JavaScript Comparison Operators: How == and === Work

You need to compare values in almost every JavaScript program. This is where comparison operators come in. They check if…

How to Use the Ternary Operator in JavaScript

The ternary operator in JavaScript keeps your code short. It helps you write conditions inside one line. JavaScript lets you…

Previous Article

HTML Syntax for Beginners: How it Works with Examples

Next Article

JavaScript Symbol Type: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.