How do you copy by value a composite data type?

--

Arrays and Objects are classified as a composite data type in JavaScript.
Composite data types are passed by reference, whereas primitive data types like integer, string are passed by the value.

Consider a composite data type ie, an array arr. we are assigning arr to arr2, another array and if we modify arr2 array, arr array also affects because by assigning arr2=arr, arr2 array is pointing to memory where arr array is pointed, so it will affect arr array if we change arr2 array. (we are using one memory location where arr and arr2 are pointing).

How to deep copy the array or copy by value ??

With the help of the spread operator (…). in javascript, we can create an array by copying by value from a source array.

var arr2 = […arr];

We can also use JSON.stringify()

let b = JSON.parse(JSON.stringify(a))
With this, You simply stringify your object and parse it right after.

var newArray = JSON.parse(JSON.stringify(orgArray));

This will create a new deep copy not related to the first one (not a shallow copy).

Also, this obviously will not clone events and functions, but the good thing you can do it within one line, and it can be used for any kind of object (arrays, strings, objects, numbers…)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vishnu Radhakrishnan O
Vishnu Radhakrishnan O

No responses yet

Write a response