JavaScript: Rest parameters

ยท

1 min read

How can I get an indefinite number of arguments as an array in a function? First, I will try this way.

const printAll = (args) => {
    console.log(args);
};

printAll(1, 3, 5, 7, 10);

image.png

I can get only the first argument of the array. That's not what I want ๐Ÿ™

This time, I will use the Rest parameters.

const printAll2 = (...args) => {
    console.log(args);
};

printAll2(1, 3, 5, 7, 10);

image.png

Now, I can get all arguments as an array. ๐Ÿ˜€

I will use the forEach, so I can print all the arguments!

const printAll3 = (...args) => {
    args.forEach((arg) => {
        console.log(arg);
    });
};
printAll3(1, 3, 5, 7, 10);

image.png

Reference: MDN Rest parameters