Object copying by reference

6 0 0
                                        

Copying - means assigning a variable or an object to another variable or object. 

Copying by value  - This applicable to the primitive types. When you copy the first variable to a second variable, you get its value. So, invoking that second variable results in accessing the value of the first variable. Like TWO PERSON STAYING IN ONE ROOM. This MIGHT be confusing, if you viewed it as a key. View it as a ROOM. 

The second person said to the first person, "I like your room, mate. I want this."

 The first person answered, "Okay, you can have it. I will take the other room". 

===================

let x = 100;

y = x;

functions displayY(){

    document.writeln('y: ${y} and x: ${x} ***');

    x = 55;

    document.writeln('y: ${y} and x: ${x} ***');

    y=200

    document.writeln('y: ${y} and x: ${x} ***');

}

==================

HTML

displayY()

Result:

y: 100 and x: 100 *** y: 100 and x: 55 *** y: 200 and x: 55 ***

Copying by reference - This is applicable to objects. When you copy the first variable which contains an object to a second variable, you get only the address of that object and not the object itself. YOU ARE USING TWO SEPARATE KEYS TO A DOOR. YOU MAKE A COPIED OF HIS KEY, SO, YOU CAN ENTER THE HOUSE. Again, view it as a ROOM. 

The second person said to the first, "I like your room mate. I want this room". 

The first answered, "We can share a room. Here is a spare key."

=================

let x = {

    "screen name": "Yagami light"

};

let y = x;

function displayY(){

    document.writeln('y: ${y["screen name"]} and x: ${x["screen name"} ***');

    x["screen name"] = "Uzumaki Naruto";

    document.writeln('y: ${y["screen name"]} and x: ${x["screen name"} ***');

    y["screen name"] = "Linda L. Taylor";

    document.writeln('y: ${y["screen name"]} and x: ${x["screen name"} ***');

}

==================

HTML

displayY()

Result:

y: Yagami Light and x: Yagami Light *** y: Uzumaki Naruto and x: Uzumaki Naruto *** y: Linda L. Taylor and x: Linda L. Taylor ***

Note: Copying by value have the option to do whatever they want while Copying by reference share a room and the changes one make, affects the other. So, if you compare the two variables who shares the same object, they are equal since they are pointing to the same object because the other copied by reference.



Javascript ProgrammingWhere stories live. Discover now