Reputation: 16233
In C/C++ I know we had pointers to objects and arrays, so they could be passed into function parameters without the need to clone said objects and arrays. In Javascript there's no such option, so we just use the object variable.
Is this good practise?
function setWhite(obj){
obj.color = "white";
}
var shirt = {
color: "red",
size: "L"
}
setWhite(shirt);
console.log(shirt);
Upvotes: 3
Views: 13890
Reputation: 4378
Yes. In javascript, objects are passed by reference. So, if you change the value of an object within the function, it changes it back outside of the function.
If you did something like this, though, it wouldn't be the case:
function setWhite(obj){
obj = {
color: "white",
size: "M"
}
}
var shirt = {
color: "red",
size: "L"
}
setWhite(shirt);
console.log(shirt); // shirt will remain red / L
Note the difference is that I'm reassigning obj
inside the setWhite()
method, so the original obj is lost to that function.
This is an important concept to understand, since it can have disturbing and unintended consequences if you let it slip your mind, accidentally changing the value on objects that you didn't want to change, just temporarily manipulate the data for some other purpose. It's especially important to keep in mind when you start working with async functions. Async functions happen in the background, and you have to specify when to 'await' for them. If you call an async function expecting it to change your objects values, but don't await it, your object might not have the updated values yet when you go to use them later in the code that calls the async function.
Similarly, if you call an async function, but don't await it, and later change the object that was passed in, by the time the async function goes to use the values from that object, they could be different than you intended when you called it.
Upvotes: 4