How to use Spread Operator 2

Posted by : on

Category : javascript


Reference


Where to use this 3. It is used when you want to put an array in the form of a parameter.


To give an example, let’s create a function.

function plus(a, b, c) {
  console.log(a + b + c);
}
plus(1, 2, 3);

I made a function called plus that takes three parameters and adds them all together.

But here When inserting parameters

Instead of directly writing 1,2,3

What if you want to insert internal data from an already existing array?

So, for example…


function plus(a, b, c) {
  console.log(a + b + c);
}

var arr = [10, 20, 30];

How can I put all the numbers 10,20,30 in arr as parameters of plus() function?


plus(10, 20, 30);

Write it by hand or


plus(arr[0], arr[1], arr[2]);

Should I do this or something?

But if that bothers you, you can use the spread operator.


function plus(a, b, c) {
  console.log(a + b + c);
}

var arr = [10, 20, 30];
plus(...arr);

Then, when printed, the result of adding 10, 20, and 30 is printed well.


About George
George

I'm George, a Web Developer.

Email : kghee9612@gmail.com

Website : https://ge5rg2.github.io

About George

Hi, my name is George. This is where I record what I have studied :D

Star
Useful Links