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,]
numsis passed by value since it is a primitive.nums, not to perform a deep modification. So even if it were an object, it would have been just reassigned, without affecting the array.