2

I'm experiencing some behaviour that I can't explain. Here is the javascript code to copy items from a source array to a destination array in 3 different ways. The first 2 run successfully, the third one doesn't.

var source = [];
source.push({id: 1, name: 'X'});
source.push({id: 2, name: 'Y'});

var dest = [];
source.forEach(i => dest.push(i));
console.log('dest 1 success');

source.forEach(pushToDest);
console.log('dest 2 success');

source.forEach(dest.push);
console.log('dest 3 success');


function pushToDest(i) {
    dest.push(i);
}

the jsfiddel can be seen at: https://jsfiddle.net/qhb6oaye/

the third way to copy the items into the new array gives following error:

Uncaught TypeError: Cannot convert undefined or null to object"

is there any hidden null/undefined objects in the forEach stream? But then why does Version 2 work? I'm confused and need help to understand this.

EasterBunnyBugSmasher
  • 1,507
  • 2
  • 15
  • 34
  • this `source.forEach(dest.push);` doesn't make sense – GrafiCode Sep 03 '22 at 16:52
  • 3
    When you pass `dest.push` as the callback, the function (`.dest()`) looses the relationship to `dest`. When it's called, it won't know what array to affect because its `this` value will be `undefined`. – Pointy Sep 03 '22 at 16:54
  • thanks. That's strange behaviour when coming from other languages – EasterBunnyBugSmasher Sep 03 '22 at 17:08
  • 1
    You'd need to use `source.forEach(dest.push, dest)` (which works the same as `source.forEach(Array.prototype.push, dest)`) – Bergi Sep 03 '22 at 17:40

0 Answers0