Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why spread operator converts object param to one item array?

Tags:

javascript

"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.

like image 795
Nicolas S.Xu Avatar asked Sep 12 '26 08:09

Nicolas S.Xu


1 Answers

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.

like image 157
CertainPerformance Avatar answered Sep 14 '26 22:09

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!