DEV Community

Abhishek Mahato
Abhishek Mahato

Posted on

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! 🚀

Top comments (0)