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"
*/
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
Thanks to @amanse
to be continue...
Top comments (0)