Translated by Mahdhi Rezvi

Like it and see. Make it a habit

In this paper,GitHub Github.com/qq449245884…Has included more categories of previous articles, as well as a lot of my documentation and tutorial material. Welcome Star and Perfect, you can refer to the examination points for review in the interview, I hope we can have something together.

As we all know, JavaScript is changing fast. There are a lot of great features in the new ES2020 that most of us can’t wait to try out. To be honest, sometimes we can write code from a different Angle and achieve the same effect, and sometimes it’s shorter and clearer.

Here is a list of some useful JavaScript tricks that will help you one day.

1. Verify method parameters

With default values for function arguments set in ES6, we can implement a neat trick to verify that method arguments cannot be empty.

const isRequired = () => { 
  throw new Error('param is required')
}

const print = (num = isRequired()) => { 
  console.log(`printing ${num}`)}print(2) //printing 2
print() // error
print(null) //printing null

Copy the code

2. Format JSON code

We’re all familiar with json.stringify, but less well known is that it can also do formatted output.

The stringify method takes three arguments: value, replacer, and space. The last two are optional parameters, which is why we rarely know about them. To indent JSON, you must use the space parameter.

console.log(JSON.stringify({name:"John",Age:23},null,'\t')); > > > {"name": "John"."Age"23} :Copy the code

3. Get the unique value from the array

To get a unique value from the array, you use the filter method to filter out duplicate values. But with the new Set native object, things are much simpler.

letUniqueArray = [...new Set([1, 2, 3,3, 3, 0, 0, 0, 0)"school"."school".'ball'.false.false.true.true])]; > > > [1, 2, 3,"school"."ball".false.true]
Copy the code

4. Remove the virtual value from the array

In some cases, we want to remove virtual values from the array. Virtual values are values in JavaScript that have a value of FALSE. There are only six virtual values in JavaScript, which are:

  • undefined
  • null
  • NaN
  • 0
  • “(null character)
  • false

The simplest way to filter these virtual values is to use the following function:

myArray.filter(Boolean)
Copy the code

Try this if you want to make some changes to the array and then filter the new array. Remember that the original myArray remains the same.

myArray
    .map(item => {
        // Do your changes and return the new item
    })
    .filter(Boolean);
Copy the code

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

5. Merge multiple objects

In practical requirements, we often need to merge multiple controls. A quick way to do this is as follows:

const user = { 
 name: 'John Ludwig', 
 gender: 'Male' 
}

const college = { 
 primary: 'Mani Primary School', 
 secondary: 'Lass Secondary School' 
}
const skills = { 
 programming: 'Extreme', 
 swimming: 'Average', 
 sleeping: 'Pro'} const summary = {... user, ... college, ... skills}Copy the code

6. Sort numeric arrays

JavaScript arrays come with built-in sort methods. By default, this sort method converts array elements to strings and lexicographically sorts them. But this can be a problem when sorting numeric arrays, and the solution is to write a sorting method by hand.

,10,4,9,123,54,1 [0]. Sort (a, b) = > (a - b) > > > [0, 1, 4, 9, 10, 54, 123]Copy the code

7. Disable the right mouse button

In some cases, we want to disable the right mouse button on a web page, we can use the following way to disable:

<body oncontextmenu="return false">
  <div></div>
</body>
Copy the code

This simple code disables right clicking.

8. Use aliases in destructions

Destruct assignment is a JavaScript expression that deconstructs values in an array or properties in an object into different variables. Instead of using existing object variables, we can rename them according to our preference.

Const object = {number: 10} const {number} = object otherNumber } = object console.log(otherNumber) //10Copy the code

9. Get the last item in the array

If you want to get the last element of an array, you can use the slice method.

let array = [0, 1, 2, 3, 4, 5, 6, 7] 
console.log(array.slice(-1))
>>>[7]

console.log(array.slice(-2))
>>>[6, 7]

console.log(array.slice(-3))
>>>[5, 6, 7]

Copy the code

10. Waiting for Promises

In some cases, we need to wait for multiple promises to end; here, we use promise.all.

const PromiseArray = [
    Promise.resolve(100),
    Promise.reject(null),
    Promise.resolve("Data release"),
    Promise.reject(new Error('Something went wrong'))];
Promise.all(PromiseArray)
  .then(data => console.log('all resolved! here are the resolve values:', data))
  .catch(err => console.log('got rejected! reason:', err))
Copy the code

One thing to note about promise.all is that this method raises an error when a Promise is rejected. This means that our code will not wait until all promises are completed.

If you want to wait until all promises are completed, whether they are rejected or successful, use promise.allSettled. This approach is in the final version of ES2020.

const PromiseArray = [
    Promise.resolve(100),
    Promise.reject(null),
    Promise.resolve("Data release"),
    Promise.reject(new Error('Something went wrong'))];
Promise.allSettled(PromiseArray).then(res =>{
console.log(res);
}).catch(err => console.log(err));
//[
//{status: "fulfilled", value: 100},
//{status: "rejected", reason: null},
//{status: "fulfilled", value: "Data release"},
//{status: "rejected", reason: Error: Something went wrong ... } / /]Copy the code

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

Original text: blog. Bitsrc. IO / 10 – super – us…


communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.