The basic usage of the comma operator

The comma operator can be used to perform multiple operations in a single statement, as follows:

Declaring multiple variables simultaneously in a single statement is the most common scenario for the comma operator. However, you can also use the comma operator to assist

The assignment. Using the comma operator to separate values in assignment eventually returns the last value in the expression:

In this example, num will be assigned to 2 because 2 is the last item in the expression. This use of the comma operator does not

It’s common, but it does exist.

Extended use of the comma operator

The comma operator also has a number of unexpected operations, such as maximizing the shorthand of our code, as shown below:

Let arr = [{id: 1, the value: ‘formal’}, {id: 2, value: ‘informal’}]

When we need to process the value of arR to {1: ‘formal ‘, 2:’ informal ‘}

In our normal writing, the reduce method is the most appropriate.

let newArr= arr.reduce((acc,item)=>{ acc[item.id]=item.value return acc },{}) console.log(newArr); When we print out newArr we get the value {1: 'formal ', 2:' informal '}Copy the code

You can see that this is also going to get us the value we want, but how do we make this code work in one line?

Here we can use the comma operator

let newArr= arr.reduce((acc,item)=> (acc[item.id]=item.value, acc),{}) console.log(newArr); Here we print the same values to get the values we want {1: 'formal ', 2:' informal '}Copy the code

Thus, the comma operator makes our code as compact as possible