3
"use strict";
let obj1 = { foo: 'bar', x: 42 };
function abc(...aaa) {
    console.log(aaa);
}
abc(obj1)
// log result: [{foo: 'bar', x: 42}]

"use strict";
let obj1 = { foo: 'bar', x: 42 };
function abc(...aaa) {
    console.log(aaa);
}
abc(obj1)
// log result: [{foo: 'bar', x: 42}]

So in the above code, obj1 is an object. So I use spread operator in the function definition, and give it an object when invoking the function. why the result is an array with one item of that input object? What is the syntax here? I didn't find any explanation in MDN about spread operator. Please help me explain.

5
  • 2
    you're mixing up rest operator and spread operator Commented Jan 23, 2021 at 17:58
  • @Syder Can you explain more? Commented Jan 23, 2021 at 17:59
  • 2
    Also neither are "operators" :) Commented Jan 23, 2021 at 18:06
  • @Pointy I see... it is called "spread syntax" in MDN. Thanks! Commented Jan 23, 2021 at 19:13
  • @NicolasS.Xu it's picky terminology but if you care about technical accuracy about language syntax, it makes a difference. Commented Jan 23, 2021 at 19:28

1 Answer 1

11

This is not spread. These are rest parameters, which collect all remaining arguments passed into a single array.

Here, there's one argument, so using rest creates an array containing just that one argument (which happens to be an object).

Here are a couple other examples that might make it clearer:

function abc(...aaa) {
    console.log(aaa);
}
abc(5, 5, 5, 5, 5)
abc(3, 1, 2, 5)
abc(1, 2, 3)
abc(0)

It'll just log all arguments passed, in the form of a single array.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.