DEV Community

Delia
Delia

Posted on

10 JavaScript Tricks You Didn't Know You Needed

JavaScript is like an ocean. No matter how much you explore, there's always something new and exciting lurking beneath the surface. For developers, the depth of JavaScript can provide endless tricks and techniques that can simplify coding tasks, optimize performance, and enhance your coding prowess. Let's dive into ten JavaScript tricks that you might not know but definitely need!

1. Destructuring Aliases

Destructuring in JavaScript is great, but did you know you can create aliases for properties? This is particularly handy when you want to avoid naming conflicts or need more descriptive variable names.

const user = { firstName: 'John', lastName: 'Doe' };
const { firstName: name, lastName: surname } = user;
console.log(name, surname); // Output: John Doe
Enter fullscreen mode Exit fullscreen mode

2. Template Literals for Dynamic Property Names

You can use template literals not just for string values, but also for property names in objects. This trick lets you dynamically create property names based on variables.

const dynamic = 'flavor';
const item = {
  [`taste${dynamic.toUpperCase()}`]: 'chocolate',
};
console.log(item.tasteFLAVOR); // Output: chocolate
Enter fullscreen mode Exit fullscreen mode

3. The Spread Operator for Object Cloning

The spread operator ... is often used for arrays, but it's also a succinct way to clone objects. This creates a shallow copy, which is perfect for avoiding accidental mutations.

const original = { a: 1, b: 2 };
const clone = { ...original };
console.log(clone); // Output: { a: 1, b: 2 }
Enter fullscreen mode Exit fullscreen mode

4. Optional Chaining Operator ?.

Avoid TypeErrors when accessing properties on undefined or null by using the optional chaining operator. This returns undefined instead of throwing an error if a reference is nullish.

const obj = { a: { b: { c: 1 } } };
const value = obj?.a?.b?.c;
console.log(value); // Output: 1
const undefinedValue = obj?.a?.nonExistent?.c;
console.log(undefinedValue); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

5. Nullish Coalescing Operator ??

Use the nullish coalescing operator to provide a default value when dealing with null or undefined. It’s a better choice than the logical OR operator || when 0 or '' (empty string) are valid values.

const count = 0;
const defaultCount = count ?? 10;
console.log(defaultCount); // Output: 0
Enter fullscreen mode Exit fullscreen mode

6. Converting to Boolean Using !!

If you need to convert a value to its boolean equivalent, double negation !! does the job quickly.

const truthyValue = 'I am truthy!';
const booleanEquivalent = !!truthyValue;
console.log(booleanEquivalent); // Output: true
Enter fullscreen mode Exit fullscreen mode

7. The at() Method for Arrays

Struggle with negative indices for array access? The at() method simplifies this by allowing negative arguments to read from the end of the array.

const array = [10, 20, 30, 40];
console.log(array.at(-1)); // Output: 40
Enter fullscreen mode Exit fullscreen mode

8. Labels for Loop Control

You can label loops and blocks in JavaScript to break or continue them from a nested loop, avoiding the need for flags or complex logic.

outer: for (let i = 0; i < 3; i++) {
  inner: for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outer;
    }
    console.log(`i=${i}, j=${j}`);
  }
}
// Output stops at i=1, j=0
Enter fullscreen mode Exit fullscreen mode

9. Quick Float to Integer Conversion

Use bitwise operators like OR | to convert floating-point numbers to integers. It’s a fast way of doing Math.floor() for positive numbers.

console.log(23.9 | 0); // Output: 23
console.log(-23.9 | 0); // Output: -23
Enter fullscreen mode Exit fullscreen mode

10. Using Set for Unique Arrays

Remove duplicates from an array swiftly by using a Set, which stores unique values.

const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

JavaScript is full of surprises, and these ten tricks are just the tip of the iceberg. Incorporate them into your daily

Top comments (0)