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.
1. Destructure and Rename in One Step
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
2. Optional Chaining with Function Calls
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
3. Use ||=
Operator for Default Assignment
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
4. Convert NodeList to Array Using Spread Operator
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
5. Array/Object Destructuring with Default Values
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
6. Remove Falsy Values from an Array
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"]
7. Sorting Arrays of Objects by Property
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 }]
8. Dynamic Imports for Lazy Loading
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();
9. Default Parameters with Object Destructuring
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
10. Use Object.assign()
for Shallow Copying
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)
Follow me on github:
11. Memoize Functions for Performance
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)
12. Using reduce
to Group Array Items
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' }] }
13. Flatten Nested Arrays with Array.flat(Infinity)
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]
14. Toggle Boolean Value with !
Toggling a boolean value is as easy as applying the NOT operator twice.
let isVisible = false;
isVisible = !isVisible;
console.log(isVisible); // true
15. Merge Multiple Arrays with concat()
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]
16. Asynchronous Array Iteration with for...of
and await
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());
}
};
17. Get the Last Item in an Array Quickly
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
18. Use Intl
for Date Formatting
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., "Monday, 25 October 2021"
19. Round Numbers with Math.round()
and Template Literals
Template literals can format rounded numbers directly.
const num = 3.14159;
console.log(`${Math.round(num * 100) / 100}`); // 3.14
20. Convert Array-Like Objects to Arrays Using Array.from()
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! ๐