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

219
Visualizações
Is it possible in Javascript to ACTUALLY pass an array as reference?

Is it possible in Javascript to pass an array (from outer scope) to a function, and mutate the original array?

I've read several answers mentioning that f()'s arr argument is actually a copy, it's name just shadows the outer scope variable. Other mention arrays are always passed by reference, but are 'copied' (that is a confusing explanation).

But if that is the case, why does arr[0] = 'a'; find the arr reference in outer scope? But arr = ['a', 'b'] does not?

If arr = ['a', 'b'] was declared in the function with a blockscoped var type (let, const), that would make more sense..

let a = [0,0,1,1,1,2,2,3,3,4];

function f(arr, z) {
  arr[0] = 'a';
  arr = ['a', 'b']
}
f(a);
console.log(a);
[ 'a', 0, 1, 1, 1, 2, 2, 3, 3, 4 ]
  1. From within f() function, the line arr[0] = 'a' modifies arr in the outer scope

  2. But the reference arr =(without aletorconst`) should also refer to outer scope?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First thing is arrays are always passed as reference in javascript.

Now coming to your question, when an array is passed to a function the argument variable of that function will hold that reference, in your case it's arr argument. If you mutate arr it will mutate original array as it is referring to original array but if you just assign some other value or reference to arr it will no longer hold reference to that original array and any changes to new reference won't have any effect on that array.

about 4 years ago · Juan Pablo Isaza Relatório

0

JavaScript is pass by value. However, when passing an object as a parameter, the value is the reference.

An array is an object. When modifying the property of an object, the change will be reflected even outside of the function scope. Thus, modifying one item (e.g, a property of the array) produces said effect. However, replacing the object will only replace the value to which said reference points toward, thus the change will only be reflected within the scope of the function.

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