1. Looping Through an Object
Use Object.entries() to loop through key-value pairs.
const person = {
name: 'Tony Stark',
age: 53,
city: 'NewYork'
};
/*
name: Tony Stark
age: 53
city: NewYork
*/
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
Explanation:
-
Object.entries()converts an object’s properties into an array of key-value pairs, making it easy to iterate over them.
2. Removing Falsy Values from an Array
Use filter(Boolean) to filter out falsy values.
(Falsy values includes false, 0, '', null, undefined, and NaN)
const arr = [1, 2, 0, '', undefined, null, 3, NaN, false];
const filteredArr = arr.filter(Boolean);
console.log(filteredArr); // [1, 2, 3]
Explanation:
- In this code,
Booleanis passed as the callback function tofilter(). - The
Boolean()function is a built-in function in JavaScript that returnstruefor truthy values andfalsefor falsy values. - By passing
Booleanas the callback function,filter()will remove all falsy values from the arrayarrand return a new arrayfilteredArrwith only truthy values.
3. Flattening a Multi-Dimensional Array
Use the flat() method to flatten arrays.
const multiDimensionalArray = [[1, 2], [3, 4, [5, 6]]];
const flattenedArray = multiDimensionalArray.flat(2);
// Output: [1, 2, 3, 4, 5, 6]
console.log(flattenedArray);
Explanation:
- In this code,
multiDimensionalArrayis a two-dimensional array with two nested arrays. - By calling the
flat()method with a depth of 2, all sub-array elements are concatenated into a single flat array. - The resulting
flattenedArraycontains all the elements of the original multi-dimensional array in a single dimension.
4. Create Array from Iterables
Use Array.from() to create an array from iterables.
// Converting String to an array
const str = "TonyStark";
const arr = Array.from(str);
// ['T', 'o', 'n', 'y', 'S', 't', 'a', 'r', 'k']
console.log(arr);
// Converting Set to an array
const set = new Set([1, 2, 3, 3, 4, 5]);
const arr = Array.from(set);
console.log(arr); // Output: [1, 2, 3, 4, 5]
Explanation:
-
Array.from()converts iterable or array-like objects like strings, Sets, Maps into arrays.
5. Extracting Values from Arrays
Use destructuring to extract values from an array.
const numbers = [1, 2, 3, 4, 5];
const [first, second, , fourth] = numbers;
console.log(first); // 1
console.log(second); // 2
console.log(fourth); // 4
Explanation:
- Destructuring lets you assign array elements to variables directly and skip unwanted values.
6. Extracting Values from Objects
Use object destructuring to extract properties.
const person = {
name: 'Tony Stark',
age: 53,
email: 'tonystark@starkindustries.com'
};
const {name, age, email} = person;
console.log(name); // Tony Stark
console.log(age); // 53
console.log(email); // tonystark@starkindustries.com
Explanation:
- Destructuring extracts object properties by matching them with variables.
7. Executing Multiple Promises in Parallel
Promise.all() allows multiple promises to be executed in parallel.
const promise1 = fetch('https://api.example.com/data1');
const promise2 = fetch('https://api.example.com/data2');
Promise.all([promise1, promise2])
.then(responses => {
// handle responses from both requests here
const [response1, response2] = responses;
// do something with the responses
})
.catch(error => {
// handle errors from either request here
console.error(error);
});
Explanation:
- In this code, we create two promises using the
fetch()method to fetch data from two different endpoints. - We then pass an array of promises to
Promise.all()which returns a new promise that resolves when all of the promises in the array have resolved. - We can then use the
responsesarray in thethen()block to handle the responses from both requests. If either promise rejects, thecatch()block will handle the error.
8. Finding the Largest and Smallest Number in an Array
Use Math.max() and Math.min() with spread syntax.
const nums = [10, 12, 29, 60, 22];
console.log(Math.max(...nums)); // 60
console.log(Math.min(...nums)); // 10
Explanation:
- Spread syntax (
...) expands the array elements, allowingMath.max()andMath.min()to evaluate them.
9. Converting Any Value to Boolean
Use double negation !! to convert values.
!!2; // true
!!''; // false
!!NaN; // false
!!'word'; // true
!!undefined; // false
Explanation:
- Double negation (
!!) in JavaScript is a trick to convert any value to its boolean equivalent. - The first
!turns truthy values tofalseand falsy values totrue, and the second!flips this boolean, resulting intruefor truthy values andfalsefor falsy values.
10. Swapping Variable Values
Use array destructuring to swap values.
let a = 5;
let b = 10;
// Swap values using array destructuring
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 5
Explanation:
- In this example, the values of
aandbare swapped without using a temporary variable. - The
[b, a]on the right side creates a new array with the values ofbanda, and then the destructuring assignment[a, b]on the left side assigns those values back toaandb, effectively swapping their values.
Top comments (0)