javascript - difference between named and anonymous callback function in JS -


i wrote following practice code compare differences between named , anonymous callback function, named callback function throws errors, wondering why , what's right way of using named callback function. looking

friends = ["john", "mike", "resch", "tony"];  friends.foreach(function(value, index) {   console.log('index of ' + index + ', value is: ' + value); });  function iterate(value, index) {   console.log('index of ' + index + ', value is: ' + value); }  friends.foreach(iterate(value, index)); 

the last line should be:

friends.foreach(iterate); 

this pass function, iterate, .foreach() can call , provide arguments parameters, value , index.

by including additional parenthesis after it, iterate being called , (attempt to) pass foreach() returned value (undefined default).

the errors because value , index don't exist outside of iterate().


for comparison, equivalent of:

friends.foreach(iterate(value, index)); 

with anonymous function be:

friends.foreach(function(value, index) {   console.log('index of ' + index + ', value is: ' + value); }(value, index)); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -