Javascript forEach function issue

function runner(note) {
note.onmousedown = keyPlay;
note.onmouseup = keyReturn;


In the code snippet above … the " notes.forEach(runner) " gives correct output but statement below it doesn’t give output … why so ? I expected second one to run and first one to not as the function runner is taking a arguement there .

How is it running when we are not giving it any sory of arguement ?

The forEach() method automatically passes arguments to the function inside of it. From this we can see that 3 arguments can be passed, the first being the current element, the second being the index of the element, and the third being the whole array. Therefore you just provide the function and the method will provide the arguments for you, as many as are possible in the function declaration.

The reason the second isn’t working is that note doesn’t actually exist. This way of doing is can work, but it’s just unnecessary as the first way is much cleaner. If you wanted to do it this way, you would need to specify note like so;

notes.forEach(note => runner(note))

and this would let it know it needs to pass the element as “note” to the function.

1 Like