chandola
chandola

Reputation: 125

Do assignment operations always copy data from right to left?

Have a look at this Javascript code:

var myString = new String();
myString.myObject = "myObject...";

//works fine as it shows "myObject..."
console.log("myString.myObject        :" + myString.myObject);
//OK myObject is also a string so it should give length and it works fine
console.log("myString.myObject.length :" + myString.myObject.length);
//it should not give anything or undefined since nothing is given to myString
console.log("myString                 :" + myString);
//myString is not yet defined so it should give undefined or 0..
console.log("myString.length          :" + myString.length);

//lets make a simple assignment
myString = myString.myObject;
//it should just copy value of myObject to myString so there are two copies of string "myObject.."

//lets log all the data all the data as i did above

console.log("myString.myObject        :" + myString.myObject);

//and this part is giving error
//console.log("myString.myObject.length :" + myString.myObject.length);

console.log("myString                 :" + myString);
console.log("myString.length          :" + myString.length);

In first half (before assignment) it is working as I have expected, but after assignment it gives an error.

It seems that myString.myObject is deleted after assignment. Is it?.

When I try to access myString.myObject the console put a red colored error. Does assignment delete myString.myObject, or something else is happening here?

Upvotes: 0

Views: 71

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382304

When you do this

myString = myString.myObject;

you're replacing the whole myString value with its myObject property value. As it doesn't have itself a myObject property, you don't have one in myString after assignment.

After this assignment, the value of myString is "myObject...".

Upvotes: 5

Related Questions