Three dots ...
is a favorite of JavaScript developers as it has many use cases.
This operator is seen in the JS concepts spread
and rest. The syntax is the same in both, but their use cases are different.
The same syntax may be confusing, but we will attempt to provide clarity.
The spread
operator is used to array
elements or object
properties
const newArray = [...oldArray, 1, 2]
const newObject = [...oldObject, newProp : 'a']
You can quickly read through the examples below to understand them better.
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)
Now, let’s check the same with objects.
const human = {name : "Kedar"}const human_age_with_spread = {...human,age : '21'}const human_age_without_spread = {human,age : '21'}console.log(human_age_with_spread)console.log(human_age_without_spread)
Rest is the collection of array
. It is primarily used to merge a list of functional arguments into an array
, i.e., you can use this when you don’t know how many arguments will be passed to your method.
Let’s look at an example:
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)
Free Resources