JavaScript is a powerful, flexible language, and knowing a few cool tricks can make your code cleaner, faster, and more efficient. Below are 20 practical JavaScript tips and tricks that you can use in real-world applications to enhance your development process.
Dev Kraken
You can rename variables during object destructuring, which is helpful when there are naming conflicts.
const user = { name: 'Alice', age: 25 };
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
console.log(userAge); // 25
Optional chaining can be used with functions, ensuring the function exists before itβs called.
const user = {
getName: () => 'Alice',
};
console.log(user.getName?.()); // Alice
console.log(user.getAge?.()); // undefined
The logical OR assignment (||=) assigns a value only if the variable is null or undefined or falsey value like 0.
let count;
count ||= 10;
console.log(count); // 10
The spread operator provides a quick way to convert a NodeList to an array.
const divs = document.querySelectorAll('div');
const divArray = [...divs];
console.log(Array.isArray(divArray)); // true
Assign default values during destructuring to avoid undefined when keys are missing.
const user = { name: 'Alice' };
const { name, age = 25 } = user;
console.log(age); // 25
Use filter() to remove falsy values (like 0, null, undefined, false) from an array.
const arr = [0, 'hello', null, 42, false, 'world'];
const filtered = arr.filter(Boolean);
console.log(filtered); // ["hello", 42, "world"]
Easily sort an array of objects by a specific property.
const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 20 }];
users.sort((a, b) => a.age - b.age);
console.log(users); // [{ name: 'Bob', age: 20 }, { name: 'Alice', age: 25 }]
Dynamic imports allow you to load modules only when needed, reducing initial load time.
const loadModule = async () => {
const module = await import('./myModule.js');
module.default(); // Calls the default export function
};
loadModule();
When using default parameters, you can also destructure and set defaults for specific properties.
function createUser({ name = 'Guest', age = 18 } = {}) {
console.log(name, age);
}
createUser(); // Guest 18
createUser({ name: 'Alice' }); // Alice 18
Object.assign() is handy for shallow-copying objects without changing the original.
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
copy.a = 3;
console.log(original.a); // 1 (unchanged)
Memoization caches results of expensive function calls based on arguments, useful for computationally heavy functions.
const memoize = (fn) => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (!cache[key]) {
cache[key] = fn(...args);
}
return cache[key];
};
};
const slowSquare = (n) => n * n;
const memoizedSquare = memoize(slowSquare);
console.log(memoizedSquare(4)); // 16 (cached on second call)
reduce() can group array items based on a property, often needed in data processing.
const people = [
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' },
{ name: 'Charlie', role: 'admin' },
];
const grouped = people.reduce((acc, person) => {
(acc[person.role] = acc[person.role] || []).push(person);
return acc;
}, {});
console.log(grouped);
// { admin: [{ name: 'Alice' }, { name: 'Charlie' }], user: [{ name: 'Bob' }] }
Flattening multi-level nested arrays becomes straightforward with Array.flat(Infinity).
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
Toggling a boolean value is as easy as applying the NOT operator twice.
let isVisible = false;
isVisible = !isVisible;
console.log(isVisible); // true
concat() is helpful for merging multiple arrays in a single statement.
const arr1 = [1, 2];
const arr2 = [3, 4];
const arr3 = [5, 6];
const merged = arr1.concat(arr2, arr3);
console.log(merged); // [1, 2, 3, 4, 5, 6]
When iterating over an array of promises, for...of with await ensures that each promise resolves before the next one runs.
const fetchData = async () => {
const urls = ['url1', 'url2'];
for (const url of urls) {
const response = await fetch(url);
console.log(await response.json());
}
};
Retrieve the last item in an array without needing to know the length.
const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4
Intl.DateTimeFormat offers a powerful way to format dates across locales.
const date = new Date();
const formatted = new Intl.DateTimeFormat('en-GB', {
dateStyle: 'full',
}).format(date);
console.log(formatted); // e.g., "Thursday, 08 August 2024"
Template literals can format rounded numbers directly.
const num = 3.14159;
console.log(`${Math.round(num * 100) / 100}`); // 3.14
Use Array.from() to convert array-like objects (e.g., arguments) into real arrays.
function example() {
const argsArray = Array.from(arguments);
console.log(argsArray);
}
example(1, 2, 3); // [1, 2, 3]
Each of these tricks simplifies common coding patterns in JavaScript. Integrate them into your workflow to write code that is both efficient and expressive.
Happy coding! π