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'
โ
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
๐ 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);
โ
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!
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]
๐ 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 }]
โ 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']
โ 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);
};
}
๐ 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);
}
};
}
โ 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()];
}
๐ 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);
};
}
โ 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
๐ 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
โ 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
๐ 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]
โ 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)