Assignment by Value Versus by Reference : Assignment « Operators « JavaScript Tutorial






When the assignment operator works on primitive values (numbers, strings, Boolean, null, and undefined), a copy of the value is made.

When the assignment operator works on JavaScript objects, references to the objects are copied.

<html>
<SCRIPT LANGUAGE="JavaScript">
<!--
    var number1 = 9;
    var arrayOfNum1 = new Array(2,6);

    var number2 = number1;
    var arrayOfNum2 = arrayOfNum1;

    number2 = 2;
    arrayOfNum2[1] = 4;

    document.write("number1=",number1,"<BR>");
    document.write("number2=",number2,"<BR>");
    document.write("arrayOfNum1[0]=",arrayOfNum1[0],"<BR>");
    document.write("arrayOfNum1[1]=",arrayOfNum1[1],"<BR>");
    document.write("arrayOfNum2[0]=",arrayOfNum2[0],"<BR>");
    document.write("arrayOfNum2[1]=",arrayOfNum2[1],"<BR>");

-->

</SCRIPT>
</html>








2.4.Assignment
2.4.1.Assignment operator
2.4.2.x += 2 (Compound Plus)
2.4.3.x -= 2 (Compound Subtraction)
2.4.4.x *= 2 (Compound Multiply)
2.4.5.x /= 2 (Multiply Divide)
2.4.6.Advanced Assignment Operators
2.4.7.Assignment by Value Versus by Reference