If you know some other tips, please leave a message~ I'm glad to add them in.
1. Mandatory parameters
ES6 provides a default parameter value mechanism, allowing you to set default values for parameters to prevent these parameters from being passed in when the function is called.
In the following example, we wrote a required() function as the default value of parameters a and b. This means that if one of the parameters a or b does not pass the value when called, the required() function will be defaulted and an error will be thrown.
const required = () => {throw new Error('Missing parameter')}; const add = (a = required(), b = required()) => a + b; add(1, 2) //3 add(1) // Error: Missing parameter.
2. Powerful reduce
The reduce method of arrays is very useful. It is generally used to define each item in an array to a single value. But you can use it to do more.
2.1 Use reduce to implement map and filter at the same time
Suppose there is now a sequence that you want to update each item of it (the function of map) and then filter out a portion (the function of filter). If you use map and filter first, you need to iterate through the array twice.
In the code below, we double the values in the sequence and then pick out those numbers greater than 50. Have you noticed how we use reduce very efficiently to complete map and filter methods at the same time?
const numbers = [10, 20, 30, 40]; const doubledOver50 = ((finalList, num) => { num = num * 2; if (num > 50) { (num); } return finalList; }, []); doubledOver50; // [60, 80]
2.2 Use reduce to replace map and filter
If you read the above code carefully, you should be able to understand that reduce can replace map and filter.
2.3 Use reduce to match brackets
Another use of reduce is to be able to match parentheses in a given string. For a string with parentheses, we need to know whether the number of (and) is consistent and (whether) is present before.
In the following code, we can easily solve this problem using reduce. We just need to declare a counter variable first, with the initial value of 0. When encountering (counter plus one, encountering) counter decrement one. If the number of left and right brackets matches, the final result is 0.
//Returns 0 if balanced. const isParensBalanced = (str) => { return ('').reduce((counter, char) => { if(counter < 0) { //matched ")" before "(" return counter; } else if(char === '(') { return ++counter; } else if(char === ')') { return --counter; } else { //matched some other char return counter; } }, 0); //<-- starting value of the counter} isParensBalanced('(())') // 0 <-- balanced isParensBalanced('(asdfds)') //0 <-- balanced isParensBalanced('(()') // 1 <-- not balanced isParensBalanced(')(') // -1 <-- not balanced
2.4 Statistics the number of the same items in the array
Many times, you want to count the number of repeated items in the array and then represent them with an object. Then you can use the reduce method to process this array.
The following code will count the number of each type of car and then represent the total number as an object.
var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota']; var carsObj = (function (obj, name) { obj[name] = obj[name] ? ++obj[name] : 1; return obj; }, {}); carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
There are so many other uses of reduce, so it is recommended to read the relevant code examples of MDN.
3. Object destruction
3.1 Delete unwanted properties
Sometimes you don't want to retain certain object properties, maybe because they contain sensitive information or are just too big. You might enumerate the entire object and delete them, but you actually just need to simply assign these useless properties to the variable and then take the useful parts you want to keep as the remaining parameters.
In the following code, we want to delete the _internal and tooBig parameters. We can assign them to internal and tooBig variables, and then store the remaining properties in the cleanObject for later use.
let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'}; (cleanObject); // {el1: '1', el2: '2', el3: '3'}
3.2 Deconstructing nested objects in function parameters
In the following code, engine is an object nested in the object car. If we are interested in the vin property of engine, it is easy to get it using deconstructed assignment.
var car = { model: 'bmw 2018', engine: { v6: true, turbo: true, vin: 12345 } } const modelAndVIN = ({model, engine: {vin}}) => { (`model: ${model} vin: ${vin}`); } modelAndVIN(car); // => model: bmw 2018 vin: 12345
3.3 Merge objects
ES6 brings the extension operator (...). It is generally used to deconstruct arrays, but you can also use it to process objects.
Next, we use the extension operator to expand a new object, and the property value in the second object overwrites the property value of the first object. For example, b and c of object2 will rewrite the attribute of object1's same name.
let object1 = { a:1, b:2,c:3 } let object2 = { b:30, c:40, d:50} let merged = {…object1, …object2} //spread and re-add into merged (merged) // {a:1, b:30, c:40, d:50}
4. Sets
4.1 Use Set to implement array deduplication
In ES6, because Set only stores unique values, you can use Set to delete duplicates.
let arr = [1, 1, 2, 2, 3, 3]; let deduped = [...new Set(arr)] // [1, 2, 3]
4.2 Using array methods for Set
Use the extension operator to simply convert Set into an array. So you can use Array's native methods for Set.
For example, we want to filter the following Set to obtain items greater than 3.
let mySet = new Set([1,2, 3, 4, 5]); var filtered = [...mySet].filter((x) => x > 3) // [4, 5]
5. Array destruction
Sometimes you will put multiple values returned by the function in an array. We can use array deconstruction to get each of them.
5.1 Numerical exchange
let param1 = 1; let param2 = 2; //swap and assign param1 & param2 each others values [param1, param2] = [param2, param1]; (param1) // 2 (param2) // 1
5.2 Receive multiple results returned by the function
In the following code, we get a post from /post and then get the relevant comments in /comments. Since we are using async/await, the function puts the return value in an array. After deconstructing the array, we can assign the return value directly to the corresponding variable.
async function getFullPost(){ return await ([ fetch('/post'), fetch('/comments') ]); } const [post, comments] = getFullPost();
Note: The original author rajaraodv, translated by Bai Yinling.