Functional programming: printing on the JS console in Chrome

I implement functional programming from Eloquent Javascript to the JS console in Google Chrome. There is a function that passes through each element in the array and performs this action in the initial parameter for the specified element.

function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); } forEach(["Wampeter", "Foma", "Granfalloon"], console.log); 

I expect the console to print every element in my array, but I get this in red:

 TypeError: 'Illegal Invocation' 

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

+4
source share
3 answers

When you pass it to forEach , the function loses a reference to its value this ( 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 do not support bind , you can use the padding on the MDN documentation page

+2
source

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);}); 
+1
source

For some reason, Chrome console.log does not work as a callback.

This code works 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]); a = ["a","b","c"]; for (i = 0; i < a.length; i++) console.log(a[i]);

I would not suggest using the JS console anyway, but it is up to you.

0
source

All Articles