0

Simple question - why

[1,2,3,4].forEach(console.log)

works fine,

let g = f => [1,2,3,4].forEach(f);
g(console.log);

works fine, but

let h = [1,2,3,4].forEach;
h(console.log)

throws Uncaught TypeError: Array.prototype.forEach called on null or undefined ?

3
  • 1
    Try let arr = [1, 2, 3, 4], h = arr.forEach.bind(arr); Commented Sep 24, 2019 at 14:58
  • 2
    Your first two examples are equivalent shorthand for [1,2,3].forEach(e => console.log(e)). The last example doesn't invoke Array.prototype.forEach. Commented Sep 24, 2019 at 14:58
  • 1
    Hi I think that forEach expect a callback as a parameter, In your first and second functions you are passing that, console.log, and f as a parameter Commented Sep 24, 2019 at 15:00

2 Answers 2

3
let x = [1,2,3,4];
let h = x.forEach.bind(x);
h(console.log)

It's because the forEach function gets unbound when you assign it to a variable. That's why this code works

https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/

Sign up to request clarification or add additional context in comments.

Comments

2

You are only taking the function forEach from the array, but you need to bind the array for iterating this array (Function#bind).

Only this step takes the array as this for the array method.

var array = [1, 2, 3, 4],
    h = Array.prototype.forEach.bind(array);

h(console.log);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.