I was reading John Resig's Learning Advanced JavaScript slides.
As i came to the slide-27, john presents a quiz as per below :
QUIZ: How can we implement looping with a callback?
function loop(array, fn){
for ( var i = 0; i < array.length; i++ ) {
// Implement me!
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
I tried to implement, and came up with following code :
function loop(array, fn){
for ( var i = 0; i < array.length; i++ ) {
fn.call(array, array[i]);
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
I was happy that it worked, and eager to see the next slide to compare it with solution john will provide in next slide.
but in next slide john provided the following solution :
function loop(array, fn){
for ( var i = 0; i < array.length; i++ )
fn.call( array, array[i], i );
}
var num = 0;
loop([0, 1, 2], function(value, i){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
to the fn function he passed to loop()
, he added another parameter i
.
that makes me wonder why another parameter is required ??
In a normal for
loop, the body has access to the index i
. If the callback solution is intended as a replacement for this, it should also have this information available. It could be useful for creating unique identifiers, for instance. So we pass it as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With