JavaScript Tips & Tricks
Let’s see some useful JavaScript tips & tricks
- Promises and Async/Await
Promises and Async/Await are invaluable for handling asynchronous operations in a more readable and maintainable way. They avoid callback hell and provide better error handling.
const fetchData = () => {
return new Promise((resolve, reject) => {
// Asynchronous operation (e.g., fetching data from a server)
setTimeout(() => {
const data = { name: 'John', age: 30 };
resolve(data); // Success
// reject(new Error('Data not found')); // Error
}, 1000);
});
};
// Using Promises
fetchData()
.then((data) => console.log(data))
.catch((error) => console.error(error.message));
// Using Async/Await
const fetchAsync = async () => {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error.message);
}
};
fetchAsync();2. Object Destructuring with renaming
When using object destructuring, you can rename variables to make your code more expressive and avoid naming conflicts.
const person = { firstName: 'John', lastName: 'Doe' };
// Renaming properties using object destructuring
const { firstName: fName, lastName: lName } = person;
console.log(fName, lName); // Output: John Doe3. reduce() Method
The
reduce()method is incredibly powerful and can be used to perform various operations on arrays, such as calculating sums, products, or transforming data.
const numbers = [1, 2, 3, 4, 5];
// Calculating the sum of all elements using reduce
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // Output: 15
// Transforming an array of objects into an object using reduce
const data = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' },
{ id: 3, name: 'Alice' },
];
const dataObject = data.reduce((acc, item) => {
acc[item.id] = item.name;
return acc;
}, {});
console.log(dataObject);
// Output:
// {
// 1: 'John',
// 2: 'Jane',
// 3: 'Alice'
// }4. Destructuring Nested Objects and Arrays
You can use destructuring not only for shallow objects and arrays but also for deeply nested ones.
const user = {
name: 'John',
age: 30,
address: {
city: 'New York',
country: 'USA',
},
hobbies: ['reading', 'coding'],
};
const {
name,
age,
address: { city, country },
hobbies: [hobby1, hobby2],
} = user;
console.log(name, age, city, country, hobby1, hobby2);
// Output: John 30 New York USA reading coding5. Function Currying
Function currying is a technique that transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. It allows you to partially apply arguments and create more specialized functions.
function add(a) {
return function (b) {
return a + b;
};
}
const add5 = add(5);
console.log(add5(3)); // Output: 8
console.log(add5(7)); // Output: 12Get Tomescu Dani’s stories in your inbox
Join Medium for free to get updates from this writer.






