4

I'm implementing functional programming from Eloquent Javascript to my JS console in Google Chrome. There's a function that loops through each element in an array and performs the given action in the initial parameter to said element.

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], console.log);

I am expecting the console to print out each item in my array, but I get this in red:

TypeError: 'Illegal Invocation'  

Is there a way I can print this on my js console or should I use something else to compile the code?

andy4thehuynh
  • 2,042
  • 3
  • 27
  • 37

3 Answers3

2

When you pass it to forEach, the function is losing the reference to its this value (the console object). The following should work:

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], console.log.bind(console));

http://jsfiddle.net/th2A5/

For browsers that don't support bind, you can use the shim available on the MDN documentation page

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
1

This should work for you...

function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
       action(array[i]);
}   

forEach(["Wampeter", "Foma", "Granfalloon"], function(x) {console.log(x);});
Smern
  • 18,746
  • 21
  • 72
  • 90
0

For some reason Chrome's console.log doesn't seem to work as a callback.

This code seems to work, though: for (item in ["a","b","c"]) console.log(item); and a = ["a","b","c"]; for (i = 0; i < a.length; i++) console.log(a[i]);

I'd not suggest using the JS console anyway, but that's up to you.

DimeCadmium
  • 314
  • 2
  • 9
  • 1
    Oh, and you could just do `["Wampeter", "Foma", "Granfalloon"].forEach(somefunction);` or etc by the way. – DimeCadmium Apr 17 '13 at 22:56
  • is there another way I can compile my code without using `alert(val)`? – andy4thehuynh Apr 17 '13 at 23:09
  • @DimeCadmium: That doesn't work for `somefunction == console.log` as well. You'd need to use `["Wampeter", "Foma", "Granfalloon"].forEach(console.log, console)` – Bergi Apr 18 '13 at 00:43
  • Ahh, THAT'S why. Right, my point wasn't that it is a solution to this problem, there's just no need to make your own forEach(array, callback) when you're provided a array.forEach(callback) by JS. – DimeCadmium Apr 19 '13 at 07:51