Friday, August 15, 2025

Javascript Module 51

  Module 51 : Optional Chaining & Nullish Coalescing

1. Introduction to Optional Chaining (?.)

✅ What is Optional Chaining?

Optional Chaining (?.) is a safe way to access nested object properties without worrying if the intermediate properties exist.


















               

 Problem It Solves:

Traditionally, accessing a  nested property required multiple checks:

let user = {}; let city = user && user.address && user.address.city; // undefined

If any intermediate property (user.address) is undefined, it throws an error:

let city = user.address.city; // ❌ TypeError: Cannot read properties of undefined

✅ Solution with Optional Chaining:

let city = user?.address?.city; // ✅ Safely returns undefined instead of throwing an error

✅ Syntax:

object?.property object?.[expression] array?.[index] function?.()


2. Optional Chaining

 Example 1: Accessing Nested Properties

const person = { name: 'John', address: { city: 'New York', }, }; console.log(person?.address?.city); // New York console.log(person?.job?.title); // undefined (no error)

 Example 2: Optional Chaining with Arrays

const users = [{ name: 'Alice' }, null, { name: 'Bob' }]; console.log(users[1]?.name); // undefined (no error) console.log(users[2]?.name); // Bob

Example 3: Optional Chaining with Functions

const user = { greet: () => 'Hello!', }; console.log(user.greet?.()); // Hello! console.log(user.nonExistent?.()); // undefined (no error)


 3. Introduction to Nullish Coalescing (??)

✅ What is Nullish Coalescing?

It provides a default value if the left-hand side is null or undefined.

               










 Difference from Logical OR (||)


|| treats falsy values like 0, "", or false as false. ?? only checks for null or undefined.

✅ Syntax:

let value = possiblyNullOrUndefined ?? defaultValue;

 Example:

let userInput = ""; let name = userInput || "Guest"; // "Guest" (because "" is falsy) let name2 = userInput ?? "Guest"; // "" (because it's not null/undefined) console.log(name); // Guest console.log(name2); // ""


4. Use Cases

 Example 1: Default Values in Settings

const settings = { theme: null, fontSize: 0, }; let theme = settings.theme ?? "light"; // "light" let fontSize = settings.fontSize ?? 14; // 0 (not replaced by 14) console.log(theme, fontSize); // light 0

 Example 2: Safe Access with Defaults

const config = { database: { retryCount: undefined, }, }; const retry = config?.database?.retryCount ?? 3; console.log(retry); // 3


 5. Exercises

✅ Exercise 1: Safe Property Access

const car = { model: 'Tesla', engine: { type: 'Electric', }, }; console.log(car?.engine?.type); // Electric console.log(car?.wheels?.count); // undefined

✅ Exercise 2: Using Nullish Coalescing

let speed = undefined; let defaultSpeed = speed ?? 60; console.log(defaultSpeed); // 60

✅ Exercise 3: Combine Both

const user = { profile: { avatar: null, }, }; const avatar = user?.profile?.avatar ?? "default.png"; console.log(avatar); // default.png


 6. Research  

  ECMAScript 2020

Both ?. and ?? were introduced in ECMAScript 2020 to reduce code complexity and improve safety when accessing potentially missing or undefined values.











                 

✅ Why Optional Chaining is Better than :

Less verbose: Reduces the need for if statements.

More readable: Easier to follow logic.

Safer: Prevents runtime crashes from accessing undefined properties.

✅ Why Nullish Coalescing is Better than ||:

|| can misinterpret falsy values (like 0, "").

?? accurately checks for absence (null/undefined) and respects valid falsy values.


  7. Tips

nested properties can crash code.

Ask output with || vs. ??.

     Visual Demos:

Use browser console or online JS playgrounds like JSFiddle, CodeSandbox.

     Discussion

 if a property doesn't exist.

 the difference between undefined and null.

 would || give unexpected results.


8. Quiz & Assignments

✅  Quiz:

What does obj?.prop do if obj is null?

What’s the output of false ?? "default"?

Difference between || and ???

✅ Mini Assignment:

    Given the following object.

Access the email safely.

Set a default profile picture if avatar is missing.

const user = { profile: { name: 'Reh', avatar: null, }, }; const email = user?.profile?.email ?? 'No email'; const avatar = user?.profile?.avatar ?? 'default.jpg'; console.log(email, avatar); // No email default.jpg


   Summary

                


Feature

Optional Chaining (?.)

Nullish Coalescing (??)

Purpose

Safe access to properties/methods

Provide default values

Handles

undefined, null

Only undefined, null

Example

obj?.prop

value ?? default



Combine Both

               










let user = { profile: null, }; let profileName = user?.profile?.name ?? "Guest"; console.log(profileName); // Guest


  References

 Optional Chaining

 Nullish Coalescing

ECMAScript 2020 Language Specification


No comments:

Post a Comment

Javascript Module 52

  Javascript   Module 52 If You want To Earn Certificate For My  All   Course Then Contact Me At My  Contact  Page   then I Will Take A Test...