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:
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:
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:
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:
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:
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:
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:
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:
Use double negation !! to convert values.
!!2; // true !!''; // false !!NaN; // false !!'word'; // true !!undefined; // false
Explanation:
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:
The above is the detailed content of Must-Know JavaScript Tips for Developers. For more information, please follow other related articles on the PHP Chinese website!