JavaScript: Rest parameters

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

No Comments Yet