DEV Community

Abhishek Mahato
Abhishek Mahato

Posted on

2 2 2 2 2

15 Essential JavaScript Tricks for Rockstar Developers๐Ÿš€

JavaScript is a powerful language, and knowing some smart tricks can make your code cleaner, more efficient, and easier to manage. Here are 15 must-know JavaScript tricks every experienced developer should master, with real-world examples!


1. Nullish Coalescing (??)

๐Ÿ”น When to use: Assign a default value only if the left operand is null or undefined.

const config = { theme: null };
const theme = config.theme ?? 'dark';
console.log(theme); // Output: 'dark'
Enter fullscreen mode Exit fullscreen mode

โœ… Unlike ||, it doesnโ€™t treat 0, false, or "" as falsy.


2. Optional Chaining (?.)

๐Ÿ”น When to use: Access deeply nested properties without checking each level.

const user = { profile: { info: { name: 'Abhi' } } };
console.log(user?.profile?.info?.name); // Output: 'Abhi'
console.log(user?.contact?.email); // Output: undefined
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Saves multiple if checks and prevents Cannot read property of undefined errors.


3. Template Literals

๐Ÿ”น When to use: Simplify string interpolation and multi-line strings.

const product = "Laptop";
const price = 1200;
const message = `The ${product} costs $${price}.`;
console.log(message);
Enter fullscreen mode Exit fullscreen mode

โœ… No more messy + string concatenations!


4. Default Parameters

๐Ÿ”น When to use: Assign default values to function arguments.

function greet(name = 'Folks') {
    return `Hey, ${name}!`;
}
console.log(greet()); // Output: Hey, Folks!
Enter fullscreen mode Exit fullscreen mode

5. Array Spread Operator (...)

๐Ÿ”น When to use: Clone or merge arrays easily.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Great for immutability and functional programming.


6. Array Filtering

๐Ÿ”น When to use: Extract elements based on a condition.

const users = [{ age: 17 }, { age: 21 }, { age: 15 }];
const adults = users.filter(user => user.age >= 18);
console.log(adults); // Output: [{ age: 21 }]
Enter fullscreen mode Exit fullscreen mode

โœ… Extract all users who are 18 or older into a new array.


7. Array Mapping

๐Ÿ”น When to use: Transform array elements.

const users = [{ name: "Alice" }, { name: "Bob" }];
const names = users.map(user => user.name);
console.log(names); // Output: ['Alice', 'Bob']
Enter fullscreen mode Exit fullscreen mode

โœ… Extracts all user names from a list of users.


8. Debouncing

๐Ÿ”น When to use: Limit how often a function is executed (e.g., for search inputs).

function debounce(func, delay) {
  let timer;
  return function(...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func(...args), delay);
  };
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Prevents excessive function calls, improving performance.


9. Throttling

๐Ÿ”น When to use: Control how often a function executes (e.g., for scroll events).

function throttle(func, limit) {
  let lastCall = 0;
  return function(...args) {
    if (Date.now() - lastCall >= limit) {
      lastCall = Date.now();
      func(...args);
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

โœ… Ensures performance efficiency in event listeners.


10. Promise.all

๐Ÿ”น When to use: Handle multiple promises in parallel.

async function fetchData() {
  const [data1, data2] = await Promise.all([fetch(url1), fetch(url2)]);
  return [await data1.json(), await data2.json()];
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Waits for multiple asynchronous operations to complete simultaneously.


11. Memoization

๐Ÿ”น When to use: Cache function results for faster repeated calls.

function memoize(fn) {
  const cache = new Map();
  return function(arg) {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}
Enter fullscreen mode Exit fullscreen mode

โœ… Boosts performance by avoiding redundant calculations.


12. String Methods (startsWith, endsWith, includes)

๐Ÿ”น When to use: Check if a string starts, ends, or contains another substring.

const str = "JavaScript Tricks";
console.log(str.includes("Tricks")); // Output: true
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ Cleaner and more readable than regex for simple string checks.


13. Number Methods

๐Ÿ”น When to use: Convert numbers safely.

console.log(Number.isInteger(42)); // Output: true
Enter fullscreen mode Exit fullscreen mode

โœ… Ensures correct number validation.


14. Intl for Formatting

๐Ÿ”น When to use: Format currency, date, and numbers effortlessly.

const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
console.log(formatter.format(1234.56)); // Output: $1,234.56
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ No need for manual string manipulation!


15. Set for Unique Values

๐Ÿ”น When to use: Store unique values efficiently.

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

โœ… Removes duplicate values automatically.


๐Ÿš€ Wrapping Up

Mastering these JavaScript tricks will boost your efficiency and make your code more maintainable. Try integrating these into your daily workflow!

๐Ÿ’ฌ Have more JavaScript tips? Drop them in the comments!

๐Ÿ“Œ Follow me on LinkedIn for more tech insights! ๐Ÿš€

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series ๐Ÿ“บ

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series ๐Ÿ‘€

Watch the Youtube series

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay