Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can't you do [array].forEach(console.log)

Tags:

javascript

going back to writing javascript for the time being, i wonder why this isn't possible

[array].forEach(console.log)
like image 754
user2167582 Avatar asked Apr 13 '26 02:04

user2167582


1 Answers

It will work correctly in certain browsers and not in others.

A major point of confusion in Javascript is the way this behaves. Often these will produce vastly different behavior:

myObj.method();

var a = myObj.method;
a();

What you are doing there is passing console.log as a function into forEach, which is separating it from the object it is attached to. This will cause any uses of this inside the log method to refer to the wrong thing, and quite possibly cause the method to not work correctly.

To remedy this, you can pass a thisArg into .forEach:

[array].forEach(console.log, console);

or use .bind():

[array].forEach(console.log.bind(console));
like image 64
JLRishe Avatar answered Apr 15 '26 16:04

JLRishe