In Javascript, we use the spread
operator to split up array elements or object properties.
Hence, the name spread, i.e., “spread the elements of an array/objects in a new array/objects”.
An example of a spread
operator with arrays is as follows:
const numbers = [1, 2, 3, 4]const numbers_with_spread = [...numbers, 5, 6]const numbers_without_spread = [numbers, 5, 6]console.log(numbers_with_spread)console.log(numbers_without_spread)
numbers
array.numbers_with_spread
using the spread operator.numbers_without_spread
without using the spread operator.An example of spread
operator using objects is as follows:
const human = {name : "Kedar"}const human_age_with_spread = {...human,age : '24'}const human_age_without_spread = {human,age : '24'}console.log(human_age_with_spread)console.log(human_age_without_spread)
human
object.human_age_with_spread
using the spread operator.human_age_without_spread
, without using the spread operator.It's a collection of remaining elements. We use it for merging a list of functional arguments into an array, i.e., we can use this when we don't know how many arguments are passed to our method.
Hence, the name rest, i.e., “the rest of the elements”.
const more_than_three = (...args) => {console.log(args) /* lets see what's in args */return console.log(args.filter((x) => x > 3))}more_than_three(1,2,3,4,5,6,7,8)
more_than_three()
using the rest operator in the arguments.3
.Note: The syntax for spread and rest is the same (`
...
`), but use-cases differ.
Free Resources