Pass by value and reference
Demonstrates the differences in Javascript of Pass by Value and Pass by Reference when passing variables to functions.
by Ron Eaglin
HTML
Value of x: <span id="xv">1</span>
<input type="button" value="Pass by Value" onclick="passByValue();" />
<br/>
<br/> Note that when the value is passed to the function which increments the passed value, the original value of the variable passed does not change. This is because the <u>value</u> is passed to the function. Incrementing this passed value will have no effect
on the original variable.
<br/>
<br/> Value of y: <span id="yv">1</span>
<input type="button" value="Pass by Reference" onclick="passByReference();" />
<br/>
<br/> In this case an object is declared and is passed to the function with the property value. Since it is an object it is passed by reference. Changes to the object properties will be refelected in the original passed object.
JavaScript
// This demonstrates a pass by value
var x = 1;
function passByValue() {
incrementX(x);
document.getElementById("xv").innerHTML = x;
}
// When the function is called and the value of x is passed
function incrementX(v) {
v++;
}
// This demonstrates a pass by reference
var y = {
value: 1
}; // y is an object
function passByReference() {
incrementY(y);
document.getElementById("yv").innerHTML = y.value;
}
// When the function is called the reference to y is passed
function incrementY(v) {
v.value++;
}