One of the main differences between reference data type and primitive data types is reference data type’s value is stored as a reference, it is not stored directly on the variable, as a value, as the primitive data types are. For example:
// The primitive data type String is stored as a value var person = "Nisar"; var anotherPerson = person; // anotherPerson = the value of person person = "Rahul"; // value of person changed console.log(anotherPerson); // Nisar console.log(person); // Rahul
It is worth noting that even though we changed person to “Rahul,” the anotherPerson variable still retains the value that person had.
Compare the primitive data saved-as-value demonstrated above with the save-as-reference for objects:
var person = {name: "Nisar"}; var anotherPerson = person; person.name = "Rahul"; console.log(anotherPerson.name); // Rahul console.log(person.name); // Rahul
In this example, we copied the person object to anotherPerson, but because the value in person was stored as a reference and not an actual value, when we changed the person.name property to “Rahul” the anotherPerson reflected the change because it never stored an actual copy of it’s own value of the person’s properties, it only had a reference to it.
No comments:
Post a Comment