poorvank
poorvank

Reputation: 7602

Why is the value of the second object not changing?

I am learning javascript. And i am confused as how the below example is working? I have created an object person and i am assigning its value to Person2.

var person = "hello";  
var Person2 = person; 
person = "hey"; 

console.log(Person2); // prints hello
console.log(person); //prints hey

Why is the value of Person2 not changing , even though person has been assigned a new value.?Is it because i am passing a reference. I am not clear with its implementation. What concept am i missing?

Upvotes: 1

Views: 87

Answers (5)

Chris Pickford
Chris Pickford

Reputation: 8991

Let's step through what's happening in your code...

1: var person = "hello";  
2: var Person2 = person; 
3: person = "hey"; 
4: console.log(Person2);
5: console.log(person);
  1. person is assigned the reference to the new string object "hello".
  2. Person2 is assigned by reference the existing string "hello".
  3. person is assigned the reference to the new string object "hey".
  4. Person2 is pointing to the "hello" string so this is output
  5. person is pointing to the "hey" string so this is output

Upvotes: 1

Adam Jenkins
Adam Jenkins

Reputation: 55613

You are dealing with a primitive in JavaScript - a string is a primitive (so is a boolean, number, undefined and null). The primitives are assigned by value, not by reference.

Arrays and objects are assigned by reference.

var person = ['test'];
var person2 = person;
person[0] = 'hi';

console.log(person); //['hi'];
console.log(person2); //['hi'];

Upvotes: 2

Michiel Dral
Michiel Dral

Reputation: 4067

Strings and numbers (primitives) are NOT passed by reference, this is only the case with objects or array (arrays are objects strictly). So assigning it to a new variable COPIES the string.

To pass it by reference you would use something like

var person = {message: "hello"};
var Person2 = person;
person.message = "Hey";

person === Person2 // true

Upvotes: 0

mayabelle
mayabelle

Reputation: 10014

You are setting the value of person2 to the value of person, then you are changing the value of person afterward. The value of person2 will not change.

Upvotes: 0

Quentin
Quentin

Reputation: 943214

It is because you are not passing a reference (at least, not one that points to person)

You haven't changed the value of Person2 so the value remains "hello" which is the only value you have assigned to it.

Upvotes: 0

Related Questions