9 JavaScript Features You’ve Never Used

4 min read 5 days ago
Published on Sep 18, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

This tutorial will explore nine lesser-known yet powerful features of JavaScript that can enhance your coding skills and prepare you for frontend interviews. By understanding and utilizing these features, you can write cleaner, more efficient code and impress potential employers.

Step 1: Use Optional Chaining

Optional chaining allows you to safely access deeply nested properties without worrying about null or undefined values.

  • Syntax: object?.property
  • Example:
    const user = { profile: { name: "Alice" } };
    const userName = user.profile?.name; // "Alice"
    const userAge = user.profile?.age; // undefined
    

Practical Tip

Use optional chaining when dealing with APIs or complex objects to avoid runtime errors.

Step 2: Nullish Coalescing Operator

This operator provides a way to set default values only when the left-hand side is null or undefined.

  • Syntax: value ?? defaultValue
  • Example:
    const input = null;
    const output = input ?? "default"; // "default"
    

Common Pitfall

Avoid confusing the nullish coalescing operator with the logical OR (||), which can return defaults for falsy values (like 0 or "").

Step 3: The flatMap Method

flatMap combines the functionality of map and flat, allowing for a one-step transformation and flattening of arrays.

  • Syntax: array.flatMap(callback)
  • Example:
    const arr = [1, 2, 3];
    const result = arr.flatMap(x => [x, x * 2]); // [1, 2, 2, 4, 3, 6]
    

Real-World Application

Use flatMap when processing lists of items that need to be transformed and flattened, such as a list of user comments with replies.

Step 4: Promise.allSettled

This method allows you to handle multiple promises and get their results regardless of whether they were fulfilled or rejected.

  • Syntax: Promise.allSettled(promisesArray)
  • Example:
    const promises = [Promise.resolve(1), Promise.reject('error'), Promise.resolve(2)];
    Promise.allSettled(promises).then(results => console.log(results));
    

Practical Tip

Use Promise.allSettled when you need to continue processing even if some promises fail, such as when fetching data from multiple APIs.

Step 5: Dynamic Importing

Dynamic importing allows you to load modules conditionally or on demand, reducing the initial load time of your application.

  • Syntax: import('module-path')
  • Example:
    if (condition) {
        import('./module.js').then(module => {
            // Use the module
        });
    }
    

Common Pitfall

Be aware that dynamic imports return a promise, so you need to handle it asynchronously.

Step 6: WeakMap and WeakSet

These data structures help manage memory more efficiently by allowing for garbage collection of their keys or values when there are no other references.

  • WeakMap: A collection of key-value pairs where keys are objects and values can be arbitrary.

  • WeakSet: A collection of unique objects.

  • Example:

    const weakMap = new WeakMap();
    const obj = {};
    weakMap.set(obj, "value");
    

Real-World Application

Use WeakMap to store private data for objects without preventing garbage collection.

Step 7: Array.prototype.at Method

The at method allows you to access elements in an array using a negative index to count from the end.

  • Syntax: array.at(index)
  • Example:
    const arr = [10, 20, 30];
    console.log(arr.at(-1)); // 30
    

Practical Tip

Use at for cleaner code when accessing the last elements of an array.

Step 8: Logical Assignment Operators

These operators combine logical operations with assignment, simplifying code.

  • Operators: &&=, ||=, ??=
  • Example:
    let a = 1;
    a ||= 2; // a remains 1
    a &&= 0; // a becomes 0
    

Common Pitfall

Ensure you're familiar with the behavior of logical operators to avoid unexpected results.

Step 9: String.prototype.replaceAll

This method allows for replacing all occurrences of a substring in a string without using regular expressions.

  • Syntax: string.replaceAll(searchValue, replaceValue)
  • Example:
    const str = "Hello World! Hello Universe!";
    const newStr = str.replaceAll("Hello", "Hi"); // "Hi World! Hi Universe!"
    

Real-World Application

Use replaceAll for straightforward text manipulation, like formatting user input or sanitizing data.

Conclusion

By incorporating these nine JavaScript features into your coding practices, you can enhance the efficiency and readability of your code. Familiarity with these features can also set you apart in frontend interviews. Explore these features further and practice integrating them into your projects for better coding skills.