My Top 10 Essential JavaScript ES6 and Beyond Syntax Shortcuts for Everyday Coding

My Top 10 Essential JavaScript ES6 and Beyond Syntax Shortcuts for Everyday Coding

Mastering the Power of Modern JavaScript Syntax for Efficient Coding

JavaScript has come a long way since its inception, evolving into a versatile language that developers across the globe rely on daily. The introduction of ECMAScript 6 (ES6) and subsequent versions has revolutionized JavaScript syntax, making it more concise and expressive. In this article, we'll explore ten indispensable JavaScript shorthand snippets and syntax improvements that have transformed the way we write code, streamlining our day-to-day development tasks. From optional chaining to object spread and rest, these modern techniques enable us to write cleaner and more efficient code. These snippets are framework agnostic and I also use them in my daily tasks and help me write cleaner code.

Optional Chaining

Optional chaining, represented by the ?. operator, is a powerful tool for accessing nested object properties safely. It eliminates the need for lengthy null or undefined checks, making your code more concise and robust. For example, user?.address?.city directly retrieves the city property, handling any potential missing values gracefully. If any of the properties is undefined, it will return undefined instead of throwing the infamous error message we all love and hate.

// Without optional chaining
const city = user.address && user.address.city;

// With optional chaining
const city = user?.address?.city;

Null Coalescing

The nullish coalescing operator (??) provides a convenient way to set default values for variables that might be null or undefined. This syntax ensures your code remains concise while offering a straightforward solution for handling missing data.

// Without Null Coalescing
const username = user.name ? user.name : "Guest";

// With Null Coalescing
const username = user.name ?? "Guest";

Using Set for removing duplicates

By converting an array into a Set and then back into an array, you can effortlessly remove duplicate elements. This approach provides a concise and efficient way to filter out unique values from an array in a single line.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)]; // [1,2,3,4,5]

Double Not Operator for Boolean Conversion

Using the double negation operator (!!) is a concise method to convert values to boolean, facilitating clearer conditional statements. For example, const hasPermission = !!user.role converts the user.role value to a boolean, indicating whether a permission exists.

Implicit Return Instead of Nested If-Else

Implicit return statements are a clean alternative to nested if-else blocks. They make functions more concise and readable. For example, const getDiscount = (total) => (total > 100 ? 20 : 10) calculates a discount based on a total amount, simplifying conditional logic.

// Without implicit return
function calculateDiscount(total) {
  let discount;
  if (total > 100) {
    discount = 20;
  } else {
    discount = 10;
  }
  return discount;
}

// With implicit return
const calculateDiscount = (total) => (total > 100 ? 20 : 10);

Short-Circuiting with || and &&

Logical operators || and && allow for concise conditional expressions with short-circuiting behavior. They simplify code by evaluating and returning values based on specific conditions, as demonstrated in const result = a || b and const value = x && y. However, there is a caveat using && inside JSX which I will discuss in my future posts.

// Using OR (||) for conditional assignment
const isAdmin = user && user.isAdmin || false;

// Equivalent code without short-circuiting
let isAdminWithoutShortCircuit;
if (user) {
  isAdminWithoutShortCircuit = user.isAdmin || false;
} else {
  isAdminWithoutShortCircuit = false;
}

// Using OR (||) to provide a default value
const username = inputUsername || "Guest";

// Using OR (||) for conditional assignment
const isAdmin = user && user.isAdmin || false;

// Short-circuiting to prevent null or undefined access
const city = user?.address?.city || "Unknown";

Deep cloning objects using structuredClone

For a long time, there was no official way for deep cloning objects. While some used JSON.stringify/JSON.parse for deep cloning and {...obj}, it was not 100% reliable as spread operator does not copy deeply nested objects and stringify will fail incase of unordered object properties. Now it can be done in one line using structuredClone method.

const myOriginal = {name : 'John'}
const myDeepCopy = structuredClone(myOriginal);

However, keep in mind there are some limitations you can see in detail here but it will cover general use cases.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm

Array .map method

The array.map method is a built-in function in JavaScript used to transform each element of an array by applying a provided function to it. It creates a new array with the results of applying the function to each element of the original array. This is a powerful tool for performing operations on arrays without modifying the original array.

// Without using array.map
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
  doubledNumbers.push(numbers[i] * 2);
}

// Using array.map
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((number) => number * 2);

Honorable mentions include other methods of Array such as forEach, find, findIndex, reduce, some, every.

Async/Await

async/await is a feature in JavaScript that simplifies working with asynchronous code, making it more readable and maintainable. It allows you to write asynchronous code in a synchronous style, which is easier to understand and reason about. async defines a function as asynchronous, while await is used within async functions to pause the execution until a promise is resolved. This combination helps you manage promises and asynchronous operations with greater clarity. It solves the problem of 'callback hell'.

// Without using async/await
function fetchData() {
  fetch('https://api.example.com/data')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network error');
      }
      return response.json();
    })
    .then(data => {
      // Handle the fetched data here
    })
    .catch(error => {
      // Handle errors
    });
}

// Using async/await
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');

    if (!response.ok) {
      throw new Error('Network error');
    }

    const data = await response.json();
    // Handle the fetched data here
  } catch (error) {
    // Handle errors
  }
}

Object Destructuring

Object destructuring is a powerful feature in JavaScript that allows you to extract values from objects and assign them to variables with a more concise and readable syntax. It simplifies the process of accessing and working with object properties, especially when dealing with nested objects. This technique can make your code cleaner and more expressive.

const person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30,
  country: 'USA'
};

// Access object properties directly
const firstName = person.firstName;
const lastName = person.lastName;
const age = person.age;

// Destructure object properties into variables
const { firstName, lastName, age } = person;

That's it! There are many more snippets out there but with these ten JavaScript shorthand snippets and syntax shortcuts, you can boost your productivity and write more maintainable code in your day-to-day development tasks. Leave a like if you found it helpful and also comment down below your most used shorthand syntaxes!