Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda