JavaScript

Value vs Reference

var n = 1;  // Variable n holds the value 1
var m = n;  // Copy by value: variable m holds a distinct value 1

function add_to_total(total, x)
{
    total = total + x;  // This line changes only the internal copy of total
}

add_to_total(n, m);

if (n == 1) m = 2;  // n contains the same value as the literal 1; m is now 2

m;
var xmas = new Date(2007, 11, 25);

var solstice = xmas;  // Both variables now refer to the same object value

solstice.setDate(21);

xmas.getDate();  // Returns 21, not the original value of 25

(xmas == solstice)  // Evaluates to true

// The two variables defined next refer to two distinct objects, both
// of which represent exactly the same date.
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);


//totals will be different after function returns
function addToTotals(totals, x)
{
    totals[0] = totals[0] + x;
    totals[1] = totals[1] + x;
    totals[2] = totals[2] + x;
}
var t = [1,2,3];
addToTotals(t,5);
xmas != solstice_plus_4

t;

José M. Vidal .

17 of 65