What is "..." in Javascript?

Asked

Viewed 48 times

1

I am studying some algorithms in Javascript, but I am doubtful in the following code:

const newArray = [...arr2];

arr2 is any array composed of numbers, for example, arr2 = [1, 2, 3].

I’d like to understand what that part means [...arr2] specifically.

1 answer

2


This is the spread syntax, or spread syntax. It allows eternal objects, such as arrays, strings, and objects, to be expanded. Maybe in the question example it does not help to understand well, but see some other examples:

With this syntax you can spread in function calls:

const lista = [1, 2, 3]

function somar(a, b, c) { return a + b + c }
somar(...lista)
// 6

Can spread in arrays, creating new arrays:

const lista = [1, 2, 3]

[10, ...lista]
// [1, 2, 3, 10]

[...lista]
// [1, 2, 3]
// simplesmente copia o array

const lista2 = [4, 5, 6]
[...lista, ...lista2]
// [1, 2, 3, 4, 5, 6]

Can spread strings, which are eternal:

[...'18']
// ['1', '8']

And it can also spread on objects:

const obj = {a: 1}
{...obj, b: 2}
// { a: 1, b: 2 }

Browser other questions tagged

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