Is a shallow copy created by spreading?

According to the example provided in the documentation,

let first:number[] = [1, 2];
let second:number[] = [3, 4];

let both_plus:number[] = [0, ...first, ...second, 5];
console.log(`both_plus is ${both_plus}`);
first[0] = 20;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);
both_plus[1]=30;
console.log(`first is ${first}`);
console.log(`both_plus is ${both_plus}`);

The concept of Spreading results in a deep copy because each array maintains its own set of values, as shown below:

both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,1,2,3,4,5
first is 20,2
both_plus is 0,30,2,3,4,5

The Documentation states that: Spreading creates a shallow copy of first and second. How can we interpret this?

Answer №1

When dealing with arrays that consist only of primitive data types, a shallow copy and deep copy are essentially the same. The true distinction arises when the array contains objects or other non-primitive elements.

In JavaScript, values are passed by value. This means that when you create a shallow copy of an array using techniques like spread syntax, each individual value within the original array is duplicated into the new array. Any modifications made to these values will not affect the original array, as they are separate entities.

However, if the array holds references to objects rather than directly storing primitive values, things get more complex. Even though a reference from the original array gets copied to the new one during a shallow copy operation, both references still point to the same underlying object. Therefore, changes made to the objects within the new array will reflect in the original array too.

For instance, consider this example:

const objArray = [{foo: "bar"}];
const shallowCopy = [...objArray];

// Modifying the structure of the array does not impact the original.
// Here, the original array retains its single item while the copy gains a second:
shallowCopy.push({foo: "baz"});
console.log("objArray after push:", objArray);
console.log("shallowCopy after push:", shallowCopy);

// Nonetheless, since both shallowCopy[0] and objArray[0] reference the same object,
// any adjustments made to either will be reflected in the other:
shallowCopy[0].foo = "something else";
console.log("objArray after mutation:", objArray);
console.log("shallowCopy after mutation:", shallowCopy);

Answer №2

When creating a shallow copy, the elements from the arrays first and second are simply added to a new array. On the other hand, in a deep copy, all elements from first and second are first duplicated and then included in the new array.

The main difference lies in whether the individual elements are duplicated into a new object before being appended to the new array.

If you test this concept with primitive values such as numbers, it may not be apparent. However, the distinction becomes evident when dealing with objects.

For instance, consider the following scenario:

let first = [{foo: 'bar'}];
let second = [{fizz: 'buzz'}];
let both = [...first, ...second];

Since spreading generates a shallow copy, the objects in question should pass an equality test:

first[0] === both[0]; // true
second[0] === both[1]; // true

Conversely, if spreading produced a deep copy, the equality test would fail:

first[0] === both[0]; // false
second[0] === both[1]; // false

Answer №3

Utilizing the spread operator creates a shallow copy

let arr1 = [{a: 1}, {b: 2}];
let arr2 = arr1;

let arr3 = [...arr1, ...arr2];
console.log(arr3); // [{a: 1}, {b: 2}, {a: 1}, {b: 2}]

arr1[1]['b'] = 10;
console.log(arr3); // [{a: 1}, {b: 10}, {a: 1}, {b: 10}]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...

The CSS styles are functioning correctly in index.html, but they are not applying properly in the component.html

When the UI Element is clicked, it should add the class "open" to the list item (li), causing it to open in a collapsed state. However, this functionality does not seem to be working in the xxx.component.html file. Screenshot [] ...

What is the best way to transfer my static files to the desired output directory in a TypeScript Express application?

I am attempting to transfer my static files from the input directory to the output directory using Express. I found guidance in this tutorial, which utilized shell.js for copying static files. The code responsible for this operation is located in CopyAsse ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Using the RabbitMQ consume method in conjunction with the channel.ack function

I'm currently working on a function in TypeScript to consume messages from my RabbitMQ: async consume( queue: string, callback: (message: ConsumeMessage | null) => void, ) { return this.channel.consume(queue, message => { c ...

What is the best method for choosing visible elements within a scrollable container?

Is there a way to retrieve the list of visible elements within a scrollable container? The number of elements that are visible on the screen changes as one scrolls, making it challenging to add a specific class to only the last two visible elements. Any s ...

What could be causing the "buffer is not a function" error to occur?

As a beginner with observables, I'm currently working on creating an observable clickstream to avoid capturing the 2 click events that happen during a double-click. However, I keep encountering this error message:- Error: Unhandled Promise rejection ...

The devastation caused by typing errors in TypeScript

I have a preference: const settings = { theme: "light", }; and feature: const Feature = ({ setting }: Props) => ( <FeatureBlock> <FeatureValue scale="large" size={20}> {setting.theme} </Styled.FeatureValue> ...

"Although the NextJS client-side data is present, it seems to be struggling to

I am facing an issue while trying to display fetched data on a blog page. Although the data is successfully retrieved client-side and I can view it using console.log(), it does not appear on the page and the elements remain empty. I am completely puzzled. ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Restricting number input value in Vue using TypeScript

I have a component that looks like this: <input class="number-input py-1 primary--text font-weight-regular" :ref="'number-input-' + title" @keypress="onKeyPressed" :disabled="disabled& ...

Leveraging scanner-js within an Angular2 environment

Exploring ways to incorporate Scanner-JS into my Angular2 project, a tool I discovered while tinkering with the framework. Being a novice in Angular2, this question might be elementary for some. I successfully installed scanner-js via npm npm install sc ...

Is Intellisense within HTML not available in SvelteKit when using TypeScript?

Having trouble with intellisense inside HTML for a simple page component. Also, renaming properties breaks the code instead of updating references. Typescript version: 4.8.4 Below is the code snippet: <script lang="ts"> import type { Bl ...

Error message in TypeScript class extension: "TypeError: Object.setPrototypeOf expects an object or null, received undefined."

In my Ionic 3 application, I have the following code snippets: @Injectable() // I also tried without @Injectable and encountered the same error export class M_someClass { constructor () { } method1 () { console.log("method1 used") } } @Injectabl ...

Tips for creating a seamless horizontal scrolling effect in Angular when hovering (automatically)

One of the components I'm working on features a gallery with an X axis orientation. <div class="gallery"> <div (mouseenter)="scrollTo('left', $event)" (mouseleave)="clearIntervalRepeater()" class="left"></div> < ...

Issue with playing audio file using HowlerJS

Having trouble playing a .mp3 file in my project directory with Howler. I'm not sure if there's an error in my src. When I tried playing an online hosted audio file, it worked fine. I've placed the audio file in the same directory as Slideon ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Provide the remaining arguments in a specific callback function in TypeScript while abiding by strict mode regulations

In my code, I have a function A that accepts another function as an argument. Within function A, I aim to run the given function with one specific parameter and the remaining parameters from the given function. Here's an example: function t(g: number, ...

Leveraging the useRoute() function with Vue 3 Composition API and Typescript: [Vue alert]: The injection "Symbol(route location)" was not detected when employing Typescript

Just recently, I upgraded a Vue 2 application that heavily uses Vue Router and TypeScript to Vue 3. During the migration process, I switched a function from reading the route using this.$route in the Options API to using useRoute() in the Composition API. ...

How to transfer data between components in Angular 6 using a service

I'm facing an issue with passing data between the course-detail component and the course-play component. I tried using a shared service and BehaviorSubject, but it didn't work as expected. Strangely, there are no errors thrown, and the data remai ...