Learn about spread operation in ReactJS

Tram Ho

Here is a tutorial on how to use the spread operator:

What is the function of the Spread Operator: clone a data but do not affect the original data

1./Copy 1 array

for an array let arr=[1,2,3,4]; To copy the normal array arr, we do the following let copy =arr

console.log( copy) //[1,2,3,4] image.png If we use Spread Operator, we use the following image.png let copy =[…arr] console.log( copy)//[1,2,3,4] image.png

if you are missing the … in the array, what will happen:

image.png it’s array in array let copy=[[1,2,3,4]], not [1,2,3,4] image.png We see the above 2 ways are the same

2./ join 2 arrays together (Concatenate arrays)

To join any two arrays together in JavaScript, we have a way like using function concat(), code image.png result image.png if using spread operation : image.png result image.png

We see the two results are the same.

Copy an object

To copy an object in the usual way, what will we use?

image.png image.png if using Spread Operator then image.png

image.png

don’t forget the sign … if you forget, the data will be

image.png image.png object in object

Merge objects together

To concatenate 2 or more objects together, we will use the function object.assign() to do it as follows: image.png

image.png when using the Spread Operator: image.png note when there are 2 data that have the same key: age has 2 data, age :25 and age: 332, because when concatenating, we let employee = {…person,…job, }; so age :332 is behind, so take the following value

image.png and if let employee = { …job,…person,}; then age : 25 image.png

note: when using Spread Operator : what data is … that data

you have array you use for array, you have obj you use for obj can’t attach obj to arr like the example below

Share the news now

Source : Viblo