These are really useful, easy-to-read tips that take advantage of modern JavaScript features to solve common problems. So whether you’re cleaning up your code or just starting a new project, these tricks can help you write more elegant and maintainable code.
Here are 9 such handy tricks that you can start using today. Let’s see what they are!
Have you ever tried flattening a deeply nested array? Previously, it meant lots of complicated loops, temporary arrays, and way too much code. But now it’s done very neatly in one powerful line of code:
Traditional
Modern
function flattenTheHardWay(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flattenTheHardWay(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Here is a shorthand command to remove duplicate elements and sort your array at the same time, perfect for cleaning up a dataset:
Traditional
Modern
function cleanArrayManually(arr) {
const unique = [];
for (let i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) {
unique.push(arr[i]);
}
}
return unique.sort((a, b) => a - b);
}
The Set will take care of removing duplicates perfectly, and then the spread operator will turn it back into an array. And you just need to call sort() afterwards!
Here's a neat command line to create a debounce version of any function - perfect for handling search input or resizing windows:
Traditional
Modern
function createDebounce(fn, delay) {
let timeoutId;
return function debounced(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(this, args);
timeoutId = null;
}, delay);
};
}
const debounce=(fn,ms)=>{let timeout;return(...args)=>{clearTimeout(timeout);timeout=setTimeout(()=>fn(...args),ms);};};
const expensiveSearch=query=>console.log('Searching for:',query);
const debouncedSearch=debounce(expensiveSearch,300);
// Use it in your event listener:
searchInput.addEventListener('input',e=>debouncedSearch(e.target.value));
This command line covers all the basic debounce use cases and saves you from calling unnecessary functions, especially when inputs are generated continuously like typing or resizing.
These snippets aren’t just about writing less code – they’re about writing smarter code. Each one solves a common JavaScript challenge in a clean, maintainable way. While these snippets are powerful, remember that readability should always come first. If a single line of code makes your code harder to understand, split it into multiple lines.