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

149
Views
Value of array is changing with value of object

When I put an object into array using push method and then change the value of the object, the value of the object in the array also changes. How to prevent it?

function onLoad() {
    let array = []
    let object = {}
    object[1] = [1,2]
    array.push(object)
    object[1] = [1,3]
    console.log(array)
}

onLoad();

I would like the code console [{1,2}] but it will console [{1,3}].

Would anyone know how to fix this?

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

0

In JavaScript, Complex data types(Objects and arrays) are copied by reference whereas primitive data types(Strings, Numbers, and Boolean) are copied by value

Simply put , Pass by reference will not create a copy instead refer to the same memory. So original objects and arrays will be changed

Copy by value will create a copy of the value and hence original value will not be changed

function change(array1){

array1[0] = "changed";

}

var original = ["original"]
change(original)

console.log(original)


function changePrimitive(input) {
  input = "changed"

}

var original = "original"


changePrimitive(original)


console.log(original);

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!