What exactly does Rest syntax return, just the elements or some special object?

Asked

Viewed 44 times

6

Doing some exercises, I realized that it is possible to use the map function in a Rest that apparently only returns pure elements. also realized that it is not possible to apply a typeof nor foreach.

Can anyone explain why? I would like to know:

  • what exactly Rest returns

  • why it is possible to apply a map, but not a foreach

  • why when in the console, apparently Rest only returns "pure elements"

sample code:

const arr = ["ana", "carlos", "rafael"]

console.log(...arr) // <- retorna os elementos apenas, sem array

console.log(...arr.map(e => e.toUpperCase())) // <- é possível usar map, como se fosse uma array

console.log(...arr.forEach(e => e.toUpperCase())) // <- não é possivel usar forEach...

1 answer

4


First of all, there’s no Rest Parameters there, and yes the Operator spread. To better understand the difference, see this answer. What it does is extract the values from the array, and pass on.

I think the best way to explain what’s going on is to simplify what each of your examples is actually passing on to the console.log.

Example 1

console.log("ana", "carlos", "rafael")

This is the simplest case: the values are unstructured from the array by the Operator spread and passed as distinct arguments to the console.log.

Example 2

console.log("ANA", "CARLOS", "RAFAEL")

In the background it is almost equal to the first, but what is unstructured is the new array returned by map – which already indicates what goes wrong in the following example. The important point here is that the map runs first, over the array, and then the spread operates over the map return (which is a new array).

Example 3

console.log(...undefined)

That’s right, test this on your console and you will see that the error is exactly the same as with yours forEach. What’s coming up for the Operator spread is the return of the forEach. And this method goes through the array and returns undefined. Like undefined it is not a collection, it cannot be running from the spread, so the error.

  • Hmm thanks buddy, I was cracking my head on this. But I still have one doubt left... are to say that the spread operator, even located in front of the elements, it only returns something after the return of the elements in front of him to it?

  • 1

    Basically yes. He’s not a real operator (it’s kind of complicated to explain), but may consider that he runs last.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.