Javascript's Spread Syntax

Spread Syntax, Explained!

Post cover displaying the title and the Javascript logo
Spread Syntax in BitCode

JavaScript introduced a bunch of new features in ES6, one of them is the Spread Syntax (also commonly called Spread Operator), and in this BitCode we will have a look at it, and its common uses.

The Syntax

The spread syntax is a sequence of three dots ..., pretty simple, the syntax allows an iterable to be expanded in other places.

The same syntax has another use in JavaScript's functions, you can learn more in this BitCode, or by clicking the link below.

Javascript’s Rest Parameters
What are the Rest Parameters in Javascript along with some usage examples.

Common Uses

There are a lot of common uses for it, let's take a look into them one by one.

Concatenate Arrays and Objects

The spread syntax allows us to concatenate multiple lists or objects in a simple syntax, Let's see the code.

Using arrays:

const arr_1 = [1, 2, 3]
const arr_2 = [4, 5, 6]

const all_arrays = [ ...arr_1, ...arr_2 ]

console.log(all_arrays)
// Output: [ 1, 2, 3, 4, 5, 6 ]

Using objects:

const obj_1 = { foo: 'foo_value' }
const obj_2 = { bar: 'bar_value' }

const object_with_all_keys = { ...obj_1, ...obj_2 }

console.log(object_with_all_keys)
// Output: { foo: 'foo_value', bar: 'bar_value' }

Deep Copy (Reference Change)

The spread syntax can also be used to make a deep copy for arrays and objects that changes the memory reference (the same result can be achieved with ES5's Object.assign).

To better see the change the spread syntax provides in this regard, let's see a typical copy and its behavior:

const obj_1 = { foo: 'foo_value' }
const obj_2 = obj_1

obj_1.foo = 'foo_value_updated'

console.log(obj_1, obj_2)
// Output: { foo: 'foo_value_updated' } { foo: 'foo_value_updated' }

As we can see, after we updated the value of foo in obj_1 the same change is reflected in obj_2 and this is unwanted behavior.

Now let's fix this by using the spread syntax:

const obj_1 = { foo: 'foo_value' }
const obj_2 = { ... obj_1 }

obj_1.foo = 'foo_value_updated'

console.log(obj_1, obj_2)
// Output: { foo: 'foo_value_updated' } { foo: 'foo_value' }

Magic, three dots solved an issue.

PS: Deep copy (clone) is not going to work with nested data structure (nested array or object).

Spread Strings

Another use is spreading a string into a list of characters.

const a_string = 'Hello World!';

const list_of_chars = [ ...a_string ]

console.log(list_of_chars)
// Output: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']