Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda