“This is the 17th day of my participation in the First Challenge 2022.


JavaScript is easy to learn, but difficult to master; It has many “quirks”, only in the long use of it, to gradually uncover its mysterious veil ~

This article brings a few snippets of JavaScript code, there are some tips, there must be you don’t know ~ blunt!

Filter the null

Filter () is used to filter “empty” values, such as null, undefined, or an empty string, using the.filter(Boolean) abbreviation.

It turns all null values to false and removes them from the list, elegant!

const groceries = ['apple', null, 'milk', undefined, 'bread', ''];

const cleanList = groceries.filter(Boolean);

console.log(cleanList);

// 'apple', 'milk', 'bread';
Copy the code

Array object deconstruction

We often use ES6 deconstruction, for an array, each item is an object, if you want to get the value of the first item of the array, you can write it like this;

const people = [ { name: "Lisa", age: 20, }, { name: "Pete", age: 22, }, { name: "Caroline", age: 60, } ]; const [{age}] = people; console.log(age); / / 20Copy the code

You can also assign an item using a comma placeholder;

const people = [
  {
    name: "Lisa",
    age: 20,
  },
  {
    name: "Pete",
    age: 22,
  },
  {
    name: "Caroline",
    age: 60,
  }
];

const [, , caroline] = people;

console.log(caroline);

//  {
//     name: "Caroline",
//     age: 60,
//   }
Copy the code

Of course, there are also common object deconstruction assignments;

const caroline = {
  firstNm: 'Caroline',
  ag: 27,
};

const {firstNm: firstName, ag: age } = caroline;

console.log(firstName, age);

// Caroline, 27
Copy the code

Separate figures

Using delimiters for large numbers greatly improves readability; This is a new feature of ES12;

const bigNumber = 1_000_000; console.log(bigNumber); / / 1000000Copy the code

Arrow functions return objects directly

Use the arrow function to return an object that, in order to distinguish it from the {function, wraps a layer around it.

const createPerson = (age, name, nationality) => ({
  age,
  name,
  nationality,
});

const caroline = createPerson(27, 'Caroline', 'US');

console.log(caroline);

// {
//   age: 27,
//   name: 'Caroline'
//   nationality: 'US',
// }
Copy the code

Await the chain

We can use filter and map methods to form a chain to filter or map the obtained data after the await method.

const chainDirectly = (await fetch('https://www.people.com'))
  .filter(person => age > 20)
  .filter(person => nationality === 'NL')
Copy the code

I’m Nuggets Anthony, output exposure input, technical insight into life, goodbye ~