Home > Web Front-end > JS Tutorial > body text

Must-Know JavaScript Tips for Developers

王林
Release: 2024-08-21 06:13:41
Original
1029 people have browsed it

Must-Know JavaScript Tips for Developers

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}`);
}
Copy after login

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]
Copy after login

Explanation:

  • In this code, Boolean is passed as the callback function to filter().
  • The Boolean() function is a built-in function in JavaScript that returns true for truthy values and false for falsy values.
  • By passing Boolean as the callback function, filter() will remove all falsy values from the array arr and return a new array filteredArr with 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); 
Copy after login

Explanation:

  • In this code, multiDimensionalArray is 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 flattenedArray contains 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);
Copy after login
// 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]
Copy after login

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
Copy after login

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
Copy after login

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);
  });
Copy after login

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 responses array in the then() block to handle the responses from both requests. If either promise rejects, the catch() 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
Copy after login

Explanation:

  • Spread syntax (...) expands the array elements, allowing Math.max() and Math.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
Copy after login

Explanation:

  • Double negation (!!) in JavaScript is a trick to convert any value to its boolean equivalent.
  • The first ! turns truthy values to false and falsy values to true, and the second ! flips this boolean, resulting in true for truthy values and false for 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
Copy after login

Explanation:

  • In this example, the values of a and b are swapped without using a temporary variable.
  • The [b, a] on the right side creates a new array with the values of b and a, and then the destructuring assignment [a, b] on the left side assigns those values back to a and b, effectively swapping their values.

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!