Learn these neat JavaScript tricks in less than 5 minutes

Some daily development tips, free translation.

Empties and truncates arrays

The easiest way to empty and truncate an array is to change the length property:

const arr = [11.22.33.44.55.66];

/ / interception
arr.length = 3;
console.log(arr); / / = > [11, 22, 33].

/ / to empty
arr.length = 0;
console.log(arr); / / = > []
console.log(arr[2]); //=> undefined
Copy the code

Simulate named parameters using object structures

Previously, when we wanted to pass multiple arguments to a function, we might use the configuration object pattern:

doSomething({ foo: 'Hello'.bar: 'Hey! '.baz: 42 });
function doSomething(config) {
  constfoo = config.foo ! = =undefined ? config.foo : 'Hi';
  constbar = config.bar ! = =undefined ? config.bar : 'Yo! ';
  constbaz = config.baz ! = =undefined ? config.baz : 13;
  // ...
}
Copy the code

This is an old but valid pattern, and with ES2015’s object structure, you can use it like this:

function doSomething({ foo = 'Hi', bar = 'Yo! ', baz = 13 }) {
  // ...
}
Copy the code

If you need this configuration object parameter to be optional, it’s also very simple:

function doSomething({ foo = 'Hi', bar = 'Yo! ', baz = 13 } = {}) {
  // ...
}
Copy the code

Object deconstruction of an array

Assign an array item to a variable using object destruction:

const csvFileLine = '1997,John Doe,US,[email protected],New York';
const { 2: country, 4: state } = csvFileLine.split(', ');
Copy the code

Note: In this case, 2 is the array subscript after split, country is the specified variable, and the value is US

switchThe scope used in the statement

Here is an example of using ranges in switch statements:

function getWaterState(tempInCelsius) {
  let state;
  
  switch (true) {
    case (tempInCelsius <= 0): 
      state = 'Solid';
      break;
    case (tempInCelsius > 0 && tempInCelsius < 100): 
      state = 'Liquid';
      break;
    default: 
      state = 'Gas';
  }
  return state;
}
Copy the code

awaitmultipleasyncfunction

Await multiple async functions and wait for them to complete, we can use promise.all:

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
Copy the code

Creating pure objects

You can create a 100% pure Object that inherits none of Object’s properties and methods (e.g. Constructor, toString(), etc.) :

const pureObject = Object.create(null);
console.log(pureObject); / / = > {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
Copy the code

formattingJSONcode

Json.stringify can not only string objects, it can also format your JSON output:

const obj = { 
  foo: { bar: [11.22.33.44].baz: { bing: true.boom: 'Hello'}}};// The third argument is the number of Spaces required for formatting
JSON.stringify(obj, null.4); 
/ / = > "{
// => "foo": {
// => "bar": [
/ / = > 11,
/ / = > 22,
/ / = > 33,
/ / = > 44
/ / = >],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
/ / = >}
/ / = >}
/ / = >}"
Copy the code

Removes array duplicates

Using the ES2015 and extension operators, you can easily remove duplicates from arrays:

const removeDuplicateItems = arr= > [...new Set(arr)];
removeDuplicateItems([42.'foo'.42.'foo'.true.true]);
//=> [42, "foo", true]
Copy the code

Note: This applies only to arrays whose contents are primitive data types

Flat multidimensional arrays

Use the extension operator to flatten an array quickly:

const arr = [11[22.33], [44.55].66];
constflatArr = [].concat(... arr);//=> [11, 22, 33, 44, 55, 66]
Copy the code

Unfortunately, the above technique only works with two-dimensional arrays, but using recursion, we can flatten an arbitrary latitude array:

function flattenArray(arr) {
  constflattened = [].concat(... arr);return flattened.some(item= > Array.isArray(item)) ? 
    flattenArray(flattened) : flattened;
}

const arr = [11[22.33], [44[55.66[77[88]], 99]]];
const flatArr = flattenArray(arr); 
//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]
Copy the code

That’s all, and hopefully the above elegant tips will help you write more beautiful JavaScript.