DEV Community

Himanshupal0001
Himanshupal0001

Posted on

3

Shallow Copy vs Deep Copy JS & Reference Part-2πŸš€

This post is continuation of the last post.

In last post we were discussing What is Reference and done with assign by value. Now we discuss furthur.

Table of content

1 Primitive Data type
2 Non-primitive data type
3 What is Reference
4 Shallow copy
5 Deep Copy

What is Reference

Assign by reference

When a non-primitive data type like array, objects or function assign to a variable and that variable point to a address of the data type is called assign by reference. We can say that non-primitive data type is basically a collection of primitive data type. Show get access to all that primitive values collectively an address is assign to the variable.
See the example below for clarification.

const student = {
  name: 'Sid',
  class: 'KG',
  subject: 'JS',
  marks: '100'
}
console.log(student);
/* output ->
name:"Sid"
class:"KG"
subject:"JS"
marks:"100"
*/

const studentCopy = student
console.log(studentCopy);
/* output ->
name:"Sid"
class:"KG"
subject:"JS"
marks:"100"
*/

//will change the name for both variables
studentCopy.name = 'Alic'
console.log('student -> ',student,'studentCopy =>', studentCopy);
/* student->
name:"Alic"
class:"KG"
subject:"JS"
marks:"100"

studentCopy ->
name:"Alic"
class:"KG"
subject:"JS"
marks:"100"
*/
Enter fullscreen mode Exit fullscreen mode

Observe the above code, a object has been created names student and it has some info about the student which is primitive data type. This data saved collectively in an object having a address on which the variable student is referencing to.

Student is assign to studentCopy variable .These two variables are pointing to the same address. If there's any change in the values it will reflect in both variables.

Suppose this as a match broadcasting live on multiple screens all at once.

Source
stackoverflow

medium

medium

dev.to

Thanks to @amanse
to be continue...

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay