Reputation: 7602
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
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);
Upvotes: 1
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
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
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
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