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

347
Vistas
Why are arrays passed by reference, but not singular variables? What is the benefit of this?

Code 1 prints "florence"

let name = "florence";

function test (arr) {
  arr += " and the machine";
}

test(name);

console.log(name);

Code 2 prints "florence and the machine"

let name = ["florence"];

function test (arr) {
  arr[0] += " and the machine";
}

test(name);

console.log(name);

I understand that the outcomes are different because Code 1 passes by value, and Code 2 passes by reference. I'm just trying to understand why.

  1. What is the benefit of retaining the mutability of an array, but not a variable?
  2. CAN YOU pass variables by reference?
  3. CAN YOU pass arrays by value (without a workaround)?
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When you pass an object (array), the referrnce to the object is passed, so in your case arr points to name.

arr[0] however now points to the value at name[0], and name[0] is modified accordingly.

Changing arr has no global effect:

let name = ["florence"];

function test (arr) {
  arr[0] += " and the machine";
  arr=[];
}

test(name);

document.write(name);

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