1

Consider the following code. Why does the forEach loop not work, but the regular for loop works?

class Nums{
 numbs: number[];
 constructor(nums: number[]){
  this.nums = nums;
 }
}

const [nums1, nums2, nums3] = [new Nums([1]), new Nums([2]), new Nums([3])];
const numSet = [nums1.nums, nums2.nums, nums3.nums];
const magicNums = [5,5,5];

//Gives wrong result.
numSet.forEach((nums) => {
 nums = magicNums;
});

console.log(nums[0]);// [1]

//Gives correct result.
for(let i=0; numSet.length; i++){
 numSet[i] = magicNums;
}

console.log(nums[0]);// [5,5,5,]
2
  • nums is passed by value since it is a primitive. Commented Oct 21, 2022 at 3:27
  • @caTS actually here OP tries to reassign nums, not to perform a deep modification. So even if it were an object, it would have been just reassigned, without affecting the array. Commented Oct 21, 2022 at 3:42

1 Answer 1

1

If you want to do the equivalent operation as in the for loop, you also have to access the original array:

numSet.forEach((_nums, index) => {
  numSet[index] = magicNums;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach


Inversely, if you do the same variable re-assignment as in your first forEach attempt within the for loop, you get the undesired result:

for (let i=0; numSet.length; i++){
  let nums = numSet[i];
  nums = magicNums; // Reassigns `nums`, but does not affect the original `numSet` array
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.