Vikram Anand Bhushan
Vikram Anand Bhushan

Reputation: 4886

Refrence datatype and primitive datatype in Javascript

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

Answers (3)

JuHwon
JuHwon

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.

enter image description here

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.

enter image description here

Upvotes: 1

Jeni
Jeni

Reputation: 430

  1. In your first example you are copying the variable's value to a new variable. Therefore 2 variables are created. So the person value is not changed (All types except objects define immutable values (values, which are incapable of being changed).)
  2. In Objects, data will be stored in heap (memory). So if you change the value of Objects[key] will change the value of that key in Main object.

For more insight see:

Upvotes: 1

Anand Deep Singh
Anand Deep Singh

Reputation: 2620

A variable can hold one of two types of values: primitive values and reference values.

  1. Primitive values are data that are stored on the stack.
  2. Primitive value is stored directly in the location that the variable accesses.
  3. Reference values are objects that are stored in the heap.
  4. Reference value stored in the variable location is a pointer to a location in memory where the object is stored.
  5. 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

Related Questions