myHotTake

Tag: optional chaining

  • How Do Babel Plugins Enable Modern JavaScript Compatibility?

    Hey there! If you find this story fun or insightful, feel free to like or share it with others who might enjoy a little JavaScript magic.


    I’m back in my high school science class, and it’s time for the big experiment. I’m like the head scientist, and I have this idea for an experiment that’s super cool but uses some pretty advanced techniques. The problem is, my classmates and I are working with basic lab kits that can’t handle all the fancy stuff I want to do.

    Enter the Babel plugins, which in our science class analogy, are like those specialized tools or ingredients I can bring from home or borrow from the teacher to make this experiment possible. Without these extra tools, my experiment wouldn’t work as planned because our basic kit just isn’t equipped to handle the complexities.

    So, I start by picking out the plugins I need. Maybe I need a special kind of thermometer to accurately measure temperature changes, or a unique chemical that isn’t available in the standard kit. Each of these represents a Babel plugin that transforms my experiment into something our basic tools can understand and execute.

    I carefully integrate these tools into my experiment setup. It’s like writing a list of plugins in my Babel configuration file. As the experiment unfolds, these special tools do their magic, allowing my classmates and me to see the results as I originally imagined, even though we’re using our basic lab kit.

    The beauty of these Babel plugins is that they allow us to bridge the gap between what we want to create and what our available tools can understand and process. My classmates are amazed as they watch the experiment succeed, and in the world of JavaScript, developers are thrilled to see their modern code run smoothly in any environment.


    Setting Up Babel with Plugins

    First, I’d set up Babel in my project. This is like gathering the special tools I need for my experiment.

    1. Install Babel:
       npm install --save-dev @babel/core @babel/cli @babel/preset-env
    1. Create a Babel Configuration File (.babelrc):
       {
         "presets": ["@babel/preset-env"],
         "plugins": [
           "@babel/plugin-proposal-optional-chaining",
           "@babel/plugin-proposal-nullish-coalescing-operator"
         ]
       }

    In this configuration, @babel/preset-env acts like the basic lab kit that sets up a broad environment for our code to run. The plugins are the special tools that allow us to use features like optional chaining (?.) and nullish coalescing (??).

    Writing Modern JavaScript

    Here’s a snippet of modern JavaScript that uses these features:

    const user = {
      profile: {
        name: "Jane Doe",
        settings: null
      }
    };
    
    const userName = user.profile?.name ?? "Guest";
    const theme = user.profile?.settings?.theme ?? "light";
    
    console.log(`Hello, ${userName}! Your theme is set to ${theme}.`);

    Without Babel and its plugins, trying to run this code in an older environment might result in errors. But with Babel in place, it transforms this code into something any JavaScript environment can understand:

    "use strict";
    
    var user = {
      profile: {
        name: "Jane Doe",
        settings: null
      }
    };
    
    var userName = (user.profile === null || user.profile === void 0 ? void 0 : user.profile.name) ?? "Guest";
    var theme = (user.profile === null || user.profile === void 0 ? void 0 : user.profile.settings.theme) ?? "light";
    
    console.log("Hello, ".concat(userName, "! Your theme is set to ").concat(theme, "."));

    Key Takeaways

    • Babel plugins act like specialized tools in a science experiment, enabling us to use advanced JavaScript features in environments that don’t natively support them.
    • Setting up Babel involves installing the core package and any necessary plugins, which are included in your configuration file.
    • Using Babel allows you to write modern JavaScript without worrying about compatibility issues across different environments.
  • 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.