Rest Operator (Javascript)

Hi everyone,

I’m trying to understand the rest operator.

Let’s assume we’ve got:

let numbers = [3, 2, 6];

function getSortedArray(numbers) {
    return array.sort();

// [2, 3, 6]

Can I use the rest operator here?

I’m sorry but I’m struggling with this concept.

I don’t understand how and where to use it

The ... operator can be used to define a rest parameter, which will collect an unknown number of function arguments into a single array. For example, if your function were changed to

function getSortedArray(...array) {
    return array.sort();

you could then call the function as getSortedArray(3, 2, 6) without having to nest 3, 2, 6 inside of square brackets. The function would create the array [3, 2, 6] for you and then sort it.

Note that this is not necessary for your original example since the intended input numbers is already in the form of an array. However, the function will not sort the array as intended since the parameter name numbers does not match the variable name array used in your function.

1 Like

Thank you so much for your explanation, it was very useful :slight_smile:

1 Like