JS Tip of the Day: Parameters are Reference Variables

Parameters are Reference Variables
Level: Advanced

JavaScript doesn’t support reference variables - variables that, when assigned, also apply their assignment to the variable that they reference (not to be confused with JavaScript object references). In C++, for example, you can specify a reference variable using &.

// C++
int main() {
   int x = 1;
   int& y = x;

   y = 2;
   std::cout << x; // 2
}

There is, however, a weird quirk in JavaScript where you can see reference variable-like behavior at work. This happens with function parameters and the arguments object. In the right circumstances, if you redefine a function parameter, the arguments object will also reflect that changed value and vice versa.

// JavaScript
function showRefs (a, b) {
    console.log(arguments); // [1, 2]
    a = 3;
    b = 4;
    console.log(arguments); // [3, 4]
    arguments[0] = 5;
    arguments[1] = 6;
    console.log(a, b); // 5, 6
}
showRefs(1, 2);

This is not a behavior you should depend on. In fact, it does not occur in strict mode or when there’s anything fancy happening in the parameter list such as default parameters or a ...rest parameter. But, if you are using the arguments object, it’s something to be conscious of, especially if you’re modifying parameter variables or mutating arguments (which you probably shouldn’t be doing anyway).

More info: