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

199
Views
Javascript reassigning array value no longer references?

Not sure how else to explain the question. Here is some very simple code to demonstrate it though.

I would expect testValue and testValue2 to be [20, 21, 22], since they are passed by reference and not passed by value, as far as I understand it, and as far as it looks like since they update with the .push() method.

Does anyone know what is happening here? Why do both testValue and testValue2 seem to start passing by value after we reassign the original array?

let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = testArray;

testArray.push(13);
testArray = [20, 21, 22];

console.log(testArray);
console.log(testValue);


//Different attempt
let testArray2 = [1, [10, 11, 12], 3, 4, 5];
let testValue2 = testArray2[1];

testArray2.push(13);
testArray2[1] = [20, 21, 22];

console.log(testArray2);
console.log(testValue2);

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

0

problem: location memory.

you create new variable testValue with testArray, this 2 variable have same location memory, then you use .push() it will push new value to location memory of variable, not depend of the array you use it.

if you not want they same location memory. use this:

// Array.from
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = Array.from(testArray);

// spread operator
let testArray = [1, [10, 11, 12], 3, 4, 5];
let testValue = [...testArray];

for more detail check this article:

  1. https://backbencher.dev/articles/javascript-variables
  2. https://medium.com/@ethannam/javascripts-memory-model-7c972cd2c239
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!