Family Magazine

Rest Pattern & Parameters JavaScript [2023] Explained Like I’m 10

By Geoff Griffiths @mmatraining1980

Rest paramaters are represented by 3 dots and then an array name

Rest Pattern & Parameters JavaScript [2023] Explained like I’m 10

It is very similar to the spread operator – using the same symbol – 3 dots.

However, the rest pattern is used within a function’s parameters

Say you have a function called sum, with 2 parameters – a + b

But we add a third argument – the third argument will normally be ignored.

Rest Pattern & Parameters JavaScript [2023] Explained like I’m 10

Using the rest parameter, as shown below, you can now store all the arguments, into an array, named “args”

Rest Pattern & Parameters JavaScript [2023] Explained like I’m 10

Now rewrite the funcition, with a loop and you can write any amount of arguments and they will be added:

Rest Pattern & Parameters JavaScript [2023] Explained like I’m 10

I asked Chat GPT to explain the rest parameter to me like I’m 10:

Imagine you and your friends are at an ice cream shop. There are lots of flavors to choose from.

Now, think of a JavaScript function as the ice cream shop owner. When you order your ice cream, you might say “I want chocolate, vanilla, and strawberry.” But your friends might order different flavors or a different number of scoops.

To handle this, the shop owner (our JavaScript function) uses a special bucket, called the “rest” parameter. No matter how many flavors you and your friends order, they all go into this same bucket.

In JavaScript, this is like when a function uses “…args” as a parameter. For example:

function orderIceCream(...flavors) { console.log(flavors); }

Here, ‘flavors’ is our special bucket. If you call orderIceCream("chocolate", "vanilla", "strawberry"), the function will print ["chocolate", "vanilla", "strawberry"]. And if your friend calls orderIceCream("mint", "rocky road"), the function will print ["mint", "rocky road"]. No matter how many flavors (or arguments) you give the function, they all get collected into the ‘flavors’ array. That’s the magic of the rest parameter!

One important thing to remember is that the rest parameter (...flavors in our example) should always be the last parameter in your function, because it’s like the shop owner’s “catch-all” bucket for all remaining ice cream flavors you order.

I hope that makes sense! Let me know if you have any other questions about JavaScript.


Back to Featured Articles on Logo Paperblog