Reputation: 4886
In the following two snippets :
var person = "Kobe";
var anotherPerson = person; // anotherPerson = the value of person
person = "Bryant"; // value of person changed
console.log(anotherPerson); // Kobe
console.log(person); // Bryant
And if we use Object :
var person = {name: "Kobe"};
var anotherPerson = person;
person.name = "Bryant";
console.log(anotherPerson.name); // Bryant
console.log(person.name); // Bryant
The first one logs "Kobe" for the variable anotherPerson
but if anotherPerson has reference to the variable person any changes happened in person should also reflect another person right ?
Can any one explain this in details
Thanks
Upvotes: 1
Views: 59
Reputation: 2063
In your first example you have 2 variables referencing to "Kobe"
. Though by assigning "Bryant"
to the person variable you are changing the reference of that variable. So in the end you got 2 variables each referencing to another string. Since primitve types in JS are immutable, there is no way to "change the value of a string". You can only assign a new string.
In your second example you are only changing the property of the object you are referencing to, though the reference stays the same of course.
Upvotes: 1
Reputation: 430
For more insight see:
Upvotes: 1
Reputation: 2620
A variable
can hold one of two types of values: primitive values and reference values.
Primitive values
are data that are stored on the stack.Primitive value
is stored directly in the location that the variable accesses.Reference values
are objects that are stored in the heap.Reference value
stored in the variable location is a pointer to a location in memory where the object is stored.Primitive types
include Undefined, Null, Boolean, Number, or String.The basics
Objects are aggregations of properties. A property can reference an object or a primitive. Primitives are values, they have no properties.
Upvotes: 1