Does JavaScript passes function arguments by value or by reference?

Saturday, Jan 11, 2020

Just like C, simple variables are passed by values to functions parameters while objects (like arrays) are passed by reference. This is illustrated with a program below that attempts to swap the two input values. Values passed directly to the function do not get swapped while the values passed as an array get swapped.

Swapping Values

// swap.js - a program to check how variables are passed to functions

function swap(a, b) // simple variables are passed by values
{
    var tmp = a;
    a = b;
    b = tmp;
}

function swap2(a) // objects, like arrays, are passed by reference
{
    var tmp = a[0];
    a[0] = a[1];
    a[1] = tmp;
}

var x = [10, 20];
console.log("first = " + x[0] + " second = " + x[1]);
swap(x[0], x[1]);
console.log("After using swap...")
console.log("first = " + x[0] + " second = " + x[1]);
swap2(x);
console.log("After using swap2...")
console.log("first = " + x[0] + " second = " + x[1]);

Results

first = 10 second = 20
After using swap...
first = 10 second = 20
After using swap2...
first = 20 second = 10