Skip to content Skip to sidebar Skip to footer

Difference Between Named And Anonymous Callback Function In Js

I wrote the following practice code to compare the differences between named and anonymous callback function, but the named callback function throws errors, I am wondering why and

Solution 1:

The last line should be:

friends.forEach(iterate);

This will pass the function, iterate, itself so that .forEach() can call it and provide arguments for its parameters, value and index.

By including the additional parenthesis after it, iterate is actually being called immediately and would (attempt to) pass forEach() its returned value (undefined by default).

The errors are likely because value and index don't exist outside of iterate().


For comparison, the equivalent of:

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

with an anonymous function would be:

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

Solution 2:

[What is the] difference between named and anonymous callback function in JS

Very little (excluding the code errors pointed out in other answers).

Given:

var data = [ ... ];

functionfoo(value, key, object){ /* do stuff */ }

then from the iterator's point of view, there is no difference between:

data.forEach(foo);

and

data.forEach(function (value, key, object){ /* do stuff */ });

In both cases, forEach is passed a reference to a function object. It doesn't know the name of the function, nor care, it just calls it and passes the required values.

So from the point of view of forEach, it doesn't matter whether the function is declared or initialised with a function expression with or without a name, the result is identical.

There is a difference inside the callback. Since in the second case no name is provided in the function expression, it can only reference itself (say for recursion) using arguments.callee, which is disliked by some and not available in strict mode.

The fix is to either use a declared function, as in the first example above, or a function expression with a name:

data.forEach(functionfoo (value, key, object){ /* foo references function */ });

the latter means that (in ECMA-262 compliant browsers) the name is only available inside the function. However, IE version 8 and lower make named function expressions named properties of the global object (more–or–less global variables), so they are generally avoided:

(function foo(){}());

alert(typeof foo);  // function in IE 8 and lower// undefined in compliant browsers

Certainly it's rare to use a recursive function in an iterator (but probably not unheard of).

Post a Comment for "Difference Between Named And Anonymous Callback Function In Js"