20 JavaScript Tricks Every Developer Mus ...

20 JavaScript Tricks Every Developer Must Know 🚀

Oct 31, 2024

image

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 0nullundefinedfalse) 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)
Vous aimez cette publication ?

Achetez un café à Safdar Ali

1 Commentaire

Plus de Safdar Ali