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

187
Views
Javascript / Typescript iteration over null-array not working with for of and forEach

If I have a null array and want to loop an object over every entry, but it doesn't work on the function loops. Example:

const myArray = [null, null, null]
myArray.forEach(e => e = {}); // a console.log reveals that the loop is running 3 times
console.log(myArray); // expected: [{}, {}, {}] reality: [null, null, null]

for(let e of myArray) {
  e = {}; // a console.log reveals that the loop is running 3 times
}
console.log(myArray); // expected: [{}, {}, {}] reality: [null, null, null]

classic for works:

for(let i = 0; i < myArray.length; i++) {
  myArray[i] = {};
}
console.log(myArray); // expected: [{}, {}, {}] reality: [{}, {}, {}]

Do I overlook something obvious?

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

0

Fundamentally, when you do:

let e = myArray[someIndex];

...you're copying the value from myArray[someIndex] to e. There is no ongoing link at that point between e and the array element, it's just that they have the same value. Both forEach and for-of, in different ways, are fundamentally doing the above. Assigning to e, in either case, won't have any effect on the array element e's value came from. It's exactly like:

let a = 1;
let b = a;  // This does not create any kind of link back to `a`...
let b = 42; // So this doesn't change `a`.

If you want to replace every element of an array:

  • If you want to update the array in place, use a classic for loop as you have in your question, or anything similar that gives you an index, and use that index to write to myArray[index].

    or

  • To create a new array of the updated values, use map:

    const newArray = myArray.map((e) => /*....*/);
    
about 4 years ago · Juan Pablo Isaza Report

0

When you loop through the array you are passing the value to the callback. Primitive values are transferred by value and not by reference so you need to access the value using an index or you can just map the array to a new one

let myArray = [null, null, null]
myArray = myArray.map(e => e = {});
console.log(myArray);

const myArray2 = [null, null, null]
myArray2.forEach((e, i) => myArray2[i] = {});
console.log(myArray2);

working example: https://jsfiddle.net/5vpxeozs/

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!