Is it correct to manipulate a function parameter inside a function?

How common (or frowned upon) is it in JavaScript good practice to modify a function parameter of a reference value of type (Object) from within the function?

Im know how it works in that all function parameters are passed by value and the reference value parameter is only a pointer to the location of the memory objects.

Thank!

edit: I've removed "pass by reference" from the title and description to make the wording more accurate and to avoid confusion for the readers. Correct answer (and helpful comments) still apply

+3


source to share


1 answer


You seem to know that it is not passed by reference, so I cannot imagine what it would look like to "handle it". Remember, because there are no missing references in JavaScript, this means you cannot communicate with the function and change the variablewhose value was passed (not the object it refers to). This is neither good nor bad practice; it's impossible.

function foo(a) {
   a  = {"different stuff": "here"};
}
var b = {stuff: "here"};
foo(b);               // `foo` assignment to `a` has nothing whatsoever
                      // to do with `b` and has no effect on it
console.log(b.stuff); // "here"

      

In general, it is perfectly acceptable to modify the state of an object through an object reference passed (by value) to a function, if that is what you are asking about:



function foo(a) {
   a.stuff = a.stuff.toUpperCase();
}
var b = {stuff: "here"};
foo(b);
console.log(b.stuff); // "HERE"

      

This has nothing to do with passing by reference.

There are programming paradigms, some of which are sometimes used in JavaScript, where it won't be good and you will have to clone and return a new object. These are not the norm in JavaScript, and if you use them, you will know. If you don't, it's standard practice to change object states like this.

+3


source







All Articles