Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Javascript is it bad practice to return an object that is passed by reference

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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
about 4 years ago · Juan Pablo Isaza Report

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!