Looks really solid, awesome work
One thing I like to do is prove it works by calling on a var that's modified inside the callback.
I'm guessing you already know this, but I'm going to show the power of callbacks by looking at a var inside and outside of callback.
This is where execution of code does not fire sequentially, the last line of code fires before the callback. Since your example is perfect we can toss in some vars and play with them without changing your code, just adding to it
[code]var lovelyPeople = ["Indsy", "Cory"];
//var to play with
var str = "qwerty";
/**
* My own lil version of the forEach function. It takes an array and a callback as a parameter.
*
* @param {array} array
* @param {function} callback It's called with the index and the array element as parameters.
* @returns {undefined}
*/
function forEachX(array, callback) {
if (typeof callback === "function") {
//simulate work that takes three seconds to complete
setTimeout(function () {
//clear our var
str = '';
for (var i = 0; i < array.length; i++) {
//assign new value for var inside callback, using your array elements
str = str + array[i];
callback(i, array[i]);
}
}, 3000);
}
}
forEachX(lovelyPeople, function (i, element) {
console.log(i + ". You're amazing " + element);
//console.log on last iteration
if (i === lovelyPeople.length - 1) {
//str outputs: array elements
console.log(str);
}
});
//str outputs: qwerty
console.log(str);
[/code]
Edit: I worry I'm being too simplistic so please don't think I'm insulting your intelligence. Your callback is perfect, that makes it so good to play around with. I just hope I'm not stating the obvious too much
08-Apr-2017 23:52:13
- Last edited on
08-Apr-2017 23:59:03
by
Lil Indecent