Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to manipulate a function parameter from within a function? [closed]

Tags:

javascript

Is it generally acceptable (or frowned upon) in good JavaScript practice to modify a function parameter of type reference value (Object) from inside a function?

I’m aware of how it works in that all function parameters are passed by value and the reference value parameter is just a pointer to an Object’s memory location.

Thank you!

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

like image 531
Dave Avatar asked Jun 29 '15 15:06

Dave


1 Answers

You seem to know that it isn't passed by reference, so I can't imagine what "treating it" like it were would look like. Remember, because there is no pass-by-reference in JavaScript, that means you can't reach out from the function and change the variable whose value was passed in (not the object it refers to). It's neither good or bad practice; it's impossible.

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

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

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

That has nothing at all to do with pass-by-reference.

There are programming paradigms, some of which are sometimes used in JavaScript, where that would not be okay and you'd have to clone and return a new object. Those are not the norm in JavaScript, and if you're using them you'll know. If you're not, it's standard practice to modify object states like that.

like image 100
T.J. Crowder Avatar answered Oct 13 '22 09:10

T.J. Crowder