DEV Community

Cover image for Mastering JavaScript Short-Hand Techniques for Cleaner Code
Vishal Yadav
Vishal Yadav

Posted on

Mastering JavaScript Short-Hand Techniques for Cleaner Code

JavaScript is a powerful and versatile language, but it can sometimes lead to verbose or repetitive code. By using JavaScript's short-hand techniques, you can write cleaner, more concise code that’s easier to maintain and understand. In this blog, we’ll explore some of the most useful JavaScript short-hand methods that will save you time and enhance readability.


1. Optional Chaining (?.)

Old Way:

if (user && user.address && user.address.city) {
  console.log(user.address.city);
}
Enter fullscreen mode Exit fullscreen mode

New Way:

console.log(user?.address?.city);
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Optional chaining allows you to access deeply nested object properties without manually checking for each level’s existence. If any property in the chain is undefined or null, the expression will short-circuit and return undefined instead of throwing an error.

Learn More about Optional Chaining


2. Array Destructuring

Old Way:

let fruits = ["apple", "banana", "mango"];
let firstFruit = fruits[0];
let secondFruit = fruits[1];
Enter fullscreen mode Exit fullscreen mode

New Way:

let [firstFruit, secondFruit] = fruits;
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Destructuring provides an elegant way to unpack values from arrays into individual variables. This is much more concise, especially when dealing with multiple values.

Learn More about Array Destructuring


3. Spread Operator (...)

Old Way:

let setA = [1, 2];
let setB = [3, 4];
let combinedSets = setA.concat(setB);
Enter fullscreen mode Exit fullscreen mode

New Way:

let combinedSets = [...setA, ...setB];
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

The spread operator allows you to easily merge arrays or objects and is more versatile than concat(). It also improves readability when combining multiple data sets.

Learn More about the Spread Operator


4. Nullish Coalescing Operator (??)

Old Way:

let output = (someValue !== null && someValue !== undefined) ? someValue : "default";
Enter fullscreen mode Exit fullscreen mode

New Way:

let output = someValue ?? "default";
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

The nullish coalescing operator checks specifically for null or undefined, whereas || checks for any falsy value, including 0, false, or ''. This makes ?? more precise when you want to allow falsy values but still provide a default for null or undefined.

Learn More about Nullish Coalescing


5. Incrementing/Decrementing

Old Way:

counter = counter + 1;
counter = counter - 1;
Enter fullscreen mode Exit fullscreen mode

New Way:

counter++;
counter--;
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

This shorthand is not only more concise but also a standard practice in most JavaScript codebases. It makes code easier to read and understand at a glance.


6. Array Mapping

Old Way:

let numbers = [1, 2, 3];
let squaredNumbers = numbers.map(function (num) {
  return num * num;
});
Enter fullscreen mode Exit fullscreen mode

New Way:

let squaredNumbers = numbers.map(num => num * num);
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Arrow functions provide a shorter syntax for mapping arrays. It eliminates the need for the function keyword and makes your code more readable, especially for simple operations.

Learn More about Array Mapping


7. Filtering Arrays with Arrow Functions

Old Way:

let ages = [18, 21, 30, 17];
let adults = ages.filter(function (age) {
  return age >= 18;
});
Enter fullscreen mode Exit fullscreen mode

New Way:

let adults = ages.filter(age => age >= 18);
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Like with array mapping, arrow functions simplify the syntax for filtering arrays. It’s more concise, making your code easier to follow.


8. Converting to Boolean

Old Way:

let isAvailable = value ? true : false;
Enter fullscreen mode Exit fullscreen mode

New Way:

let isAvailable = !!value;
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Using !! is a clever trick to convert any value to a Boolean. This is particularly useful when you want to quickly check if a value is truthy or falsy without a lengthy ternary expression.


9. Rounding Numbers with Bitwise Operators

Old Way:

let roundedNumber = Math.round(price);
Enter fullscreen mode Exit fullscreen mode

New Way:

let roundedNumber = ~~(price + 0.5);
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

The ~~ operator is a shorthand method to round numbers by stripping off the decimal part using a bitwise trick. However, use this carefully as it only works for positive numbers.


10. Swapping Variables

Old Way:

let temp = x;
x = y;
y = temp;
Enter fullscreen mode Exit fullscreen mode

New Way:

[x, y] = [y, x];
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Destructuring assignment allows you to swap variables in one clean line without needing a temporary variable. This is a sleek, modern technique for swapping values in JavaScript.


11. Template Literals

Template literals provide an easy way to work with strings that include variables or expressions without needing concatenation.

Old Way:

const name = 'John';
const greeting = 'Hello, ' + name + '!';
Enter fullscreen mode Exit fullscreen mode

New Way:

const name = 'John';
const greeting = `Hello, ${name}!`;
Enter fullscreen mode Exit fullscreen mode

Why It's Better:

Template literals are more readable and allow for multi-line strings without needing escape characters.

Learn More about Template Literals


12. Short-Circuit Evaluation

You can use logical operators like && and || as shorthand for conditional statements.

Example with AND (&&):

Old Way:

if (isLoggedIn) {
    goToHomepage();
}
Enter fullscreen mode Exit fullscreen mode

New Way:

isLoggedIn && goToHomepage();
Enter fullscreen mode Exit fullscreen mode

This technique is particularly useful in React for conditional rendering:

<div>{isLoggedIn && <UserProfile />}</div>
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Using JavaScript short-hand techniques is an excellent way to write more efficient, readable code. Not only do they reduce verbosity, but they also align your code with modern best practices. Start incorporating these tips into your codebase today to streamline your workflow and impress fellow developers with cleaner, more concise code!


References

  1. JavaScript Shorthand Techniques - Plain English
  2. Mastering JavaScript Shorthand Techniques - DEV Community
  3. Top JavaScript Shorthand Techniques - OpenReplay Blog
  4. 25+ JavaScript Shorthand Coding Techniques - SitePoint
  5. JavaScript Shorthand Techniques — Ultimate Cheat-Sheet - LinkedIn

If you found this guide useful, please consider sharing it with others! 😊

Top comments (0)