Better Programming

Advice for programmers.

Follow publication

Member-only story

Understanding the JavaScript Spread Operator — Advanced Uses

Introduction

The spread operator, , was first introduced in ES6. It quickly became one of the most popular features. So much so that, despite the fact it only worked on arrays, a proposal was made to extend its functionalities to objects. This feature was finally introduced in ES9.

The goal of this tutorial, which is divided into two parts, is to show you why the spread operator should be used, how it works, and to deep dive into its uses, from the most basic to the most advanced.

If you haven’t read the first part of this tutorial, I encourage you to do so!

Here is a summary of the contents of this tutorial:

Part 1

  1. Why the spread operator should be used.
  2. Cloning arrays/objects.
  3. Converting array-like structures to array.
  4. The spread operator as an argument.
  5. BAdding elements to arrays/objects.
  6. Merging arrays/objects.

Part 2

  1. Destructuring nested elements.
  2. Adding conditional properties.
  3. Short-circuiting.
  4. The rest parameter .
  5. Default destructuring values.
  6. Default properties.

Cloning Arrays/Objects With Nested Elements

In the first part of this article, we learned about reference data types, accidental variable mutation, and how we could solve this problem by cloning arrays/objects immutably, with the spread operator.

However, there’s a slight problem with this approach when it comes to nested reference data types. The spread operator only performs a shallow clone.

What does this mean? If we attempt to clone an object that contains an array, for example, the array inside the cloned object will contain a reference to the memory address where the original array is stored…

This means that, while our object is immutable, the array inside it isn’t. Here’s an example to illustrate this:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Estefanía García Gallardo
Estefanía García Gallardo

Written by Estefanía García Gallardo

Just a person who’s in love with computer sciences 💕💕 Developer of Npkill ~ https://npkill.js.org/

Responses (2)

Write a response