roray
roray

Reputation: 756

Why do I have to use both rest parameter and spread operator in the below example?

function f(...y){
      y.forEach(v => {
        console.log("111");
        console.log(v);
      });
    }

var z=["a","b","c","d","e","f"];

f(z);

Expected output:

"111"
"a"
"111"
"b"
"111"
"c"
"111"
"d"
"111"
"e"
"111"
"f"

Actual output:

"111"
["a", "b", "c", "d", "e", "f"]

Only when I change the line f(z) to f(...z) I get the expected output. I am new to ECMAScript 2015. Please tell me what am I missing here.

Upvotes: 0

Views: 39

Answers (1)

hityagi
hityagi

Reputation: 5256

f(z) means only one argument (in this case, an array) is passed to the method, while f(...z) means, the values in array are passed as parameter to the function.

Read More :

  1. Spread operator
  2. Rest parameters

function f(...y){
      console.log(y.length);
    }

var z=["a","b","c","d","e","f"];
f(z);
f(...z);

Upvotes: 3

Related Questions