myHotTake

Tag: runtime safety

  • How Does Optional Chaining Prevent JavaScript Errors?

    Hey, if you find this story helpful, feel free to give it a like or share it with others who might enjoy it!


    I’m in a bookstore, filled with endless rows of shelves. Each shelf is stacked with books that hold the secrets of the universe. Some books are easy to find, while others are hidden in nooks and crannies. My mission? To find a specific book that contains the answer to a burning question.

    Now, here’s the twist: not every shelf has the book I’m looking for, and some sections of the bookstore are under renovation, meaning the shelves might not even exist. If I charge straight ahead without checking, I could end up bumping into walls or tripping over construction tools.

    So, I decide to use a special pair of glasses called “Optional Chaining Glasses.” These glasses let me peek into each section of the bookstore safely. With them, I can easily check if a shelf exists and if the book is there without stumbling around. If there’s no shelf or book, I simply move on without a scratch or a misstep.

    In the world of JavaScript, optional chaining is like these glasses. It allows me to safely navigate through potentially undefined objects and properties without causing a runtime error. If an object or property doesn’t exist, JavaScript just returns undefined instead of throwing an error, allowing my code to continue its journey smoothly.

    So, in essence, optional chaining is my trusty tool for exploring the unpredictable terrain of JavaScript objects, ensuring I avoid those pesky runtime errors as I seek out the hidden knowledge in the bookstore of code.


    Suppose I want to find out the author of a book located deep within the nested shelves. In vanilla JavaScript, without optional chaining, I’d have to cautiously check each shelf like this:

    if (bookstore && bookstore.section && bookstore.section.shelf && bookstore.section.shelf.book) {
        console.log(bookstore.section.shelf.book.author);
    } else {
        console.log('Book or author not found');
    }

    This code checks every step of the way to ensure that each object exists before attempting to access the next one. It’s like me checking if each shelf in the bookstore exists before reaching for a book.

    Now, with optional chaining, I can don those glasses and simplify my journey:

    console.log(bookstore?.section?.shelf?.book?.author ?? 'Book or author not found');

    This single line of code safely navigates through the nested objects. The ?. operator checks if the preceding property exists, and if it doesn’t, it stops and returns undefined. The ?? operator then provides a fallback message if undefined is returned.

    Key Takeaways:

    1. Simplicity and Safety: Optional chaining simplifies code by reducing the need for repetitive checks. It safely handles cases where properties might be undefined, preventing runtime errors.
    2. Cleaner Code: By using ?., code becomes more readable and concise, making it easier to maintain and understand.
    3. Fallback Values: Combining optional chaining with the nullish coalescing operator (??) provides a graceful way to handle missing values by setting default responses.