user99999 user99999 - 2 months ago 5
Javascript Question

Passing variable by full reference

I want to pass an object or array to a function, make it undefined, and see the changes after the function execution ends.

var arr = ['aaa', 'bbb', 'ccc'];
var reset = function (param) {
param[0] = 'bbb';
param = undefined;
}
reset(arr);


All right, so the result is
['bbb', 'bbb', 'ccc']
, but I want it to be
undefined
. Is it possible to do this efficiently?

Answer

JavaScript is a pass by value language, so modifying the value of a function parameter inside the function cannot have an effect on the variable passed as the argument.

If you want to do something like that, you can have your function return the value:

var reset = function(param) {
  // think think think
  if (whatever)
    return undefined;
  return param;
};

arr = reset(arr);

Now, if the function decides that the right thing to do is empty out the source variable, it returns undefined.

If you just want to clear the variable, however, there's no need for a function:

arr = undefined;
Comments