Assignment |
Active Web |
The value of a variable is set by the assignment operator (=).
If the assigned data is another variable then the value is either a reference to, or a copy of the assigned variable. If the assigned variable is a primitive object then the value is a copy of the variable and if the variable is an ordinary object (created with the new operator) then the value is a reference to the object.
It is important you realize the difference between assigning by value and assigning by reference.
If the data for the assignment is a primitive object (null, boolean, number or string) then the variable is given a copy of the data. This copy is completely separate from the original data and can be changed independently of the data.
e.g. var myData = “hello?;
var myVariable = myData;
In this example we now have two copies of the string "hello", and changing myVariable will have no affect on myData.
If the data for the assignment is a non-primitive object (i.e. any object created with the new operator or any object that has been given properties) then the variable is given a reference to the object not a copy of the object. If the original data object is changed then the reference will also see the change, and vice versa, if the reference is changed then the original data is changed.
e.g. var myData = “hello?;
myData.name = “jo?;
var myVariable = myData;
In this example myVariable has a reference to myData as the primitive string object was given a property and thus converted it to non primitive. If myVariable.name is changed then myData.name is also changed.
When an assignment takes place then the variable is replaced by the new data (either a reference or a copy). This means that you can not change the value of an object. If you create an object that has a value and has properties then assigning a new value to that variable replaces the object thus losing its properties.
e.g. var person1 = “George?;
person1.age = 56;
person1 = “Harry?;
In this example assigning the string "Harry" to the variable person1 has lost the age property as the variable person1, which was a string object with a value of "George" and a property of age, is now a primitive string object with a value of "Harry".
If a variable is assigned to 'null' then the object and all its properties are deleted and replaced by the primitive null object.
Note that a property that has no value and has no properties of its own, does not exist. If you set a property but do not assign it any value then it does not exist.
e.g. house.chair;
This statement will not create the property chair in the object house.
Topic ID: 150034