JavaScript is a powerful, flexible language, and knowing a few cool tricks can make your code cleaner, faster, and more efficient. JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like React Native), of the server side (like NodeJS ) and has many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino) Below are 20 practical JavaScript tips and tricks that you can use in real-world applications to enhance your development process.
Table of Contents
- Remove Falsy Values from an Array
- Optional Chaining with Function Calls
- Default Parameters with Object Destructuring
- Memoize Functions for Performance
- Flatten Nested Arrays with
Array.flat(Infinity)
- Toggle Boolean Value with
!
- Destructure and Rename in One Step
- Convert Array-Like Objects to Arrays Using
Array.from()
- Round Numbers with
Math.round()
and Template Literals - Get the Last Item in an Array Quickly
- Merge Multiple Arrays with
concat()
- Using
reduce
to Group Array Items - Array/Object Destructuring with Default Values
- Use
||=
Operator for Default Assignment - Convert NodeList to Array Using Spread Operator
- Use
Object.assign()
for Shallow Copying - Sorting Arrays of Objects by Property
- Asynchronous Array Iteration with
for...of
andawait
- Dynamic Imports for Lazy Loading
- Use
Intl
for Date Formatting
1. Remove Falsy Values from an Array
Filter out falsy values (0
, null
, undefined
, false
) from an array in one line.
const arr = [0, 'hello', null, 42, false, 'world'];
const filtered = arr.filter(Boolean);
console.log(filtered); // ["hello", 42, "world"]
2. Optional Chaining with Function Calls
Ensure that a function exists before calling it using optional chaining.
const user = { getName: () => 'Alice' };
console.log(user.getName?.()); // Alice
console.log(user.getAge?.()); // undefined
3. Default Parameters with Object Destructuring
Set default parameters and destructure them in one go.
function createUser({ name = 'Guest', age = 18 } = {}) {
console.log(name, age);
}
createUser(); // Guest 18
createUser({ name: 'Alice' }); // Alice 18
4. Memoize Functions for Performance
Cache results of expensive function calls for faster performance.
const memoize = (fn) => {
const cache = {};
return (...args) => {
const key = JSON.stringify(args);
if (!cache[key]) cache[key] = fn(...args);
return cache[key];
};
};
const memoizedSquare = memoize(n => n * n);
console.log(memoizedSquare(4)); // 16 (cached)
5. Flatten Nested Arrays with Array.flat(Infinity)
Flatten arrays to any depth effortlessly.
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
6. Toggle Boolean Value with !
Easily toggle a boolean variable by applying the !
operator.
let isVisible = false;
isVisible = !isVisible;
console.log(isVisible); // true
7. Destructure and Rename in One Step
Rename variables while destructuring.
const user = { name: 'Alice', age: 25 };
const { name: userName, age: userAge } = user;
console.log(userName); // Alice
console.log(userAge); // 25
8. Convert Array-Like Objects to Arrays Using Array.from()
Convert array-like objects (like arguments
) into true arrays.
function example() {
const argsArray = Array.from(arguments);
console.log(argsArray);
}
example(1, 2, 3); // [1, 2, 3]
9. Round Numbers with Math.round()
and Template Literals
Format rounded numbers within template literals.
const num = 3.14159;
console.log(`${Math.round(num * 100) / 100}`); // 3.14
10. Get the Last Item in an Array Quickly
Retrieve the last item in an array without knowing its length.
const arr = [1, 2, 3, 4];
console.log(arr.at(-1)); // 4
11. Merge Multiple Arrays with concat()
Combine multiple arrays easily with concat()
.
const arr1 = [1, 2];
const arr2 = [3, 4];
const merged = arr1.concat(arr2);
console.log(merged); // [1, 2, 3, 4]
12. Using reduce
to Group Array Items
Use reduce()
to group items based on properties.
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);
13. Array/Object Destructuring with Default Values
Assign default values during destructuring.
const user = { name: 'Alice' };
const { name, age = 25 } = user;
console.log(age); // 25
14. Use ||=
Operator for Default Assignment
Assign a value if the variable is null, undefined, or falsey.
let count;
count ||= 10;
console.log(count); // 10
15. Convert NodeList to Array Using Spread Operator
Quickly convert a NodeList
to an array.
const divs = document.querySelectorAll('div');
const divArray = [...divs];
console.log(Array.isArray(divArray)); // true
16. Use Object.assign()
for Shallow Copying
Make a shallow copy of an object with Object.assign()
.
const original = { a: 1, b: 2 };
const copy = Object.assign({}, original);
copy.a = 3;
console.log(original.a); // 1
17. Sorting Arrays of Objects by Property
Sort objects in an array 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);
18. Asynchronous Array Iteration with for...of
and await
Process array items asynchronously with for...of
and await
.
const fetchData = async () => {
const urls = ['url1', 'url2'];
for (const url of urls) {
const response = await fetch(url);
console.log(await response.json());
}
};
19. Dynamic Imports for Lazy Loading
Load modules only when needed using dynamic imports.
const loadModule = async () => {
const module = await import('./myModule.js');
module.default(); // Calls the default export function
};
loadModule();
20. Use Intl
for Date Formatting
Format dates across locales using Intl.DateTimeFormat
.
const date = new Date();
const formatted = new Intl.DateTimeFormat('en-GB', {
dateStyle: 'full',
}).format(date);
console.log(formatted); // e.g., "Monday, 25 October 2021"
Each of these JavaScript tricks is designed to make your code more expressive and efficient. Integrate them into your workflow, and you’ll see the difference in your productivity and code readability!
Happy coding! 🚀
Tech Wizard
Published on
Trick or Treat?