Translator: although the skills are good, the emphasis is on mastering and using it!

  • Learn these neat JavaScript tricks in less than 5 minutes
  • Translator: Fundebug

To ensure readability, free translation rather than literal translation is used in this paper. In addition, the copyright of this article belongs to the original author, and translation is for study only.

1. Delete the last element of the array

A simple way to clear or delete the end of an array is to change the length property of the array.

const arr = [11.22.33.44.55.66];
// truncanting
arr.length = 3;
console.log(arr); / / = > [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); / / = > []
console.log(arr[2]); //=> undefined
Copy the code

2. Use object deconstruction to simulate named parameters

If you need to pass a list of options to a function as arguments, you might prefer to use an Object to define the Config.

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 effective, way of emulating named parameters in JavaScript. However, the way you handle config in doSomething is a bit cumbersome. In ES2015, you can use object deconstruction directly.

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

If you want this parameter to be optional, that’s easy too.

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

3. Use object deconstruction to work with arrays

We can use object deconstruction syntax to get the elements of an array:

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

4. Use range values in switch statements

You can use the following technique to write switch statements that satisfy ranges:

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

Await multiple async functions

We can await multiple async functions with promise.all while using async/await.

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

6. Create a pure object

You can create a 100% pure Object that inherits no properties or methods from Object (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

7. Format JSON code

Json.stringify can not only char an object, but also format the output JSON object.

const obj = { 
  foo: { bar: [11.22.33.44].baz: { bing: true.boom: 'Hello'}}};// The third parameter is the number of spaces used to 
// beautify the JSON output.
JSON.stringify(obj, null.4); 
/ / = > "{
// => "foo": {
// => "bar": [
/ / = > 11,
/ / = > 22,
/ / = > 33,
/ / = > 44
/ / = >],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
/ / = >}
/ / = >}
/ / = >}"
Copy the code

8. Remove duplicate elements from the array

In ES2015, there is a syntax for collections. Repeating elements can be easily removed by using the set syntax and Spread operation:

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

Tiling multidimensional arrays

Using the Spread operation, it is easy to tile a nested multidimensional array:

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

Unfortunately, the above method only works for two-dimensional arrays. By recursion, however, we can tile nested arrays of any dimension.

unction 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! I hope these tips will help you write more beautiful JS code! If that’s not enough, use Fundebug as an aid!

Select comments

  • Ethan B Martin: The switch is cleverly written, but not recommended. Please do not encourage developers to write JS code in this way. One of our engineers wrote this, which later caused a lot of reading pain during code review. Fortunately, we refactored it into more readable code in time. Compare the difference between using swtich and if:

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

    The second method has several advantages: A) less code and easier to read; B) You don’t need to declare a local variable, the reader doesn’t have to keep track of how you made changes to the variable; C) Switch (true) is really confusing.

  • Flo Sloot: Great article! Tip 6 is not recommended unless you absolutely have to use it. Because it is slow to execute and takes up more space. Because V8 doesn’t optimize for empty objects.