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

120
Views
problem with js loops and array of objects

I have a question about js loops and how they really work. I'm looping trough an array of objects that looks like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

The loop just updates the value of every element:

array.forEach(el => {
        el.value = 1;
        console.log(array)
})

The thing that I don't understand is why the output looks like this:

[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

And not like this:

[{value: 1}, {value: 0}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 0}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 0}]
[{value: 1}, {value: 1}, {value: 1}, {value: 1}]

What am I missing?

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

0

I'm guessing that you are trying to look at the output on the dev tools on Chrome, and on the dev tools, you see a reference to the array. meaning that at the end of the execution all the items have value = 1, so the dev tools shows your the same reference to the array.

To see the actual values at the moment of execution (instead of reference) use JSON.stringify like this:

const array = [{value: 0}, {value: 0}, {value: 0}, {value: 0}];

array.forEach(el => {
        el.value = 1;
        console.log(JSON.stringify(array))
});
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!