Swastik Yadav

S Y

Navigate back to the homepage

Copy by value vs copy by reference

Swastik Yadav
June 18th, 2021 · 1 min read

Hello Everyone

When we copy a datatype in JavaScript, there are two different ways the datatype can be copied - by value or by reference.

In this post we will explore what it means to copy by value and copy by reference.

Copy by value

All primitive datatypes are copied by value. Let’s see an example.

1let string1 = "Hello";
2
3let string2 = string1;
4
5console.log(string1, string2);
6// Hello Hello
7
8string1 = "World";
9
10console.log(string1, string2);
11// World Hello

In the above code string2 copies the value of string1, and when value of string1 changes it does not affect the copied value of string2 because both string1 and string2 refers to different points in memory.

copy-by-value

That’s what it means to copy by value.

Copy by reference

Objects are copied by reference. Let’s see an example.

1let person1 = {
2 name: "Swastik",
3 age: 22,
4}
5
6let person2 = person1;
7
8console.log(person1["name"], person2["name"]);
9// Swastik Swastik
10
11person1["name"] = "Rahul";
12
13console.log(person1["name"], person2["name"]);
14// Rahul Rahul

In the above code snippet person2 copies the reference of person1, so when person1 changes it also affects the person2 because both person1 and person2 refers to the same point in memory.

copy-by-reference

That’s what it means to copy by reference.


If you want to learn more about duplicating and cloning JavaScript primitives and objects, please read this article - Shallow cloning vs Deep cloning


Thank You, for reading. If you found this post helpful please do share and subscribe to my newsletter below or here.

More articles from Swastik Yadav

Difference between for-of and and for-in loop

Let's clear the confusion between for of and for in loop once and for all.

June 18th, 2021 · 1 min read

Truthy and Falsy values in JavaScript

Learn which are the only 6 falsy values in JavaScript.

June 11th, 2021 · 1 min read

DiaryOfADev, Success stories of underdog developers.

Every week we share an underdog developer's story and a deep dive into a programming concept.

© 2021–2024 Swastik Yadav
Link to $https://github.com/SwastikyadavLink to $https://www.linkedin.com/in/swastikyadav/