The Journey of #100DaysOfCode (@Ayman_Dandan)

๐ƒ๐š๐ฒ ๐Ÿ’ of 100DaysOfCode

  • ๐™๐™š๐™จ๐™ฉ ๐™‹๐™–๐™ง๐™–๐™ข๐™š๐™ฉ๐™š๐™ง๐™จ -

Before knowing what rest parameters are, I would like to talk first about the โ€˜argumentsโ€™ object in JS.

The โ€˜argumentsโ€™ object is an ๐˜ข๐˜ณ๐˜ณ๐˜ข๐˜บ-๐˜ญ๐˜ช๐˜ฌ๐˜ฆ object that is found as a local variable within all ๐˜ฏ๐˜ฐ๐˜ฏ-๐˜ข๐˜ณ๐˜ณ๐˜ฐ๐˜ธ functions. You can refer to a functionโ€™s arguments inside that function by using its โ€˜argumentsโ€™ object.
I said it is an array-like object; since, like arrays, they have entries for each argument the function was called with, with the first entryโ€™s index at 0(ex. arguments[0]), and the function length is also included within. However, they donโ€™t have other array functions like forEach and map functions.

The โ€˜argumentsโ€™ object can access any argument of a function even when not specified in the declaration of the said function, which means that the function would have access for infinite arguments.

Now back to rest parameters :sweat_smile:
much like โ€˜argumentsโ€™, they allow the function to have access to indefinite number of arguments as an ๐’‚๐’“๐’“๐’‚๐’š.

A function definitionโ€™s last parameter can be prefixed with " โ€ฆ " which will cause all remaining (user supplied) parameters to be placed within an Array object.

Rest Parameters are not limited to only the length function, they can perform what any array can do like using slice, forEach, map, sort, etcโ€ฆ
As they are used as the last parameter, it leaves space for other parameters to be specified.

3 Likes