JavaScript spread operator

Understand the basics of JavaScript Spread operator

You can use the spread operator to expand an array, object or string....

Let's start with an array example. given

const a = [1, 2, 3]

You can create a new array using

const b = [...a, 4, 5, 6]

You can also create a copy of the array using

const c = [...a]

This also applies to objects. Clone object:

const newObj = { ...oldObj }

With strings, the spread operator creates an array with each character in the string:

const hey = 'hey'
const arrayized = [...hey] // ['h', 'e', 'y']

This operator has some very useful applications. One of the most important features is the ability to use arrays as function parameters in a very simple way:

const f = (foo, bar) => {}
const a = [1, 2]
f(...a)

ThisRest elementUseful when in useArray deconstruction:

const numbers = [1, 2, 3, 4, 5]
const [first, second, ...others] = numbers

withSpread element:

const numbers = [1, 2, 3, 4, 5]
const sum = (a, b, c, d, e) => a + b + c + d + e
const result = sum(...numbers)

ES2018 introduces other attributes, and the remaining attributes are the same as the object.

Rest attributes:

const { first, second, ...others } = {
  first: 1,
  second: 2,
  third: 3,
  fourth: 4,
  fifth: 5
}

first // 1 second // 2 others // { third: 3, fourth: 4, fifth: 5 }

Spread attributeAllows to create new objects by combining the properties of the objects passed after the spread operator:

const items = { first, second, ...others }
items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }

This is also the perfect way to merge two simple objects into one:

const object1 = {
  name: 'Flavio'
}

const object2 = { age: 35 }

const object3 = {…object1, …object2 }

Download mine for freeJavaScript beginner's manual


More js tutorials: