Home > Enterprise >  Javascript is it bad practice to return an object that is passed by reference
Javascript is it bad practice to return an object that is passed by reference

Time:04-06

Let's say I have this function in JavaScript:

function foo(a) {
  a.item = "four"
  return a
}

b = {
  item: "three"
}
b = foo(b)
console.log(b)

Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:

function foo(a) {
  a.item = "four"
  return a
}

b = {
  item: "three"
}
foo(b)
console.log(b)

Is it bad practice to use return b for better readability even though it is not needed

Are there any downsides to returning the object?

CodePudding user response:

The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.

Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.

sorted_words = string.split(" ").sort();

If it didn't return the array, you'd have to do this in two steps:

sorted_words = string.split(" ")
sorted_words.sort();

CodePudding user response:

You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.

However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.

Following that idea, your example would look like:

function foo(a) {
  // Copy our input (assuming 'a' only contains primitive values)
  const output = { ...a };
  output.item = 'four';
  return output;
}

const b = { item: 'three' };
const c = foo(b);

// b is unchanged
  • Related