Long story short, I don’t understand callbacks.
I just finished the JS: Next Steps Sitepoint course a few days ago hoping to have a more illuminating explanation of callbacks than what was offered in the Intro to JS course but I was sorely disappointed.
So I’ve been googling for an explanation of it online but I can’t seem to find any that doesn’t end up being a jQuery tutorial or something about AJAX or, recently, NodeJS.
I can somewhat understand stuff like this:
someDOMElement.addEventListener("click", function()
{
console.log("This is a callback function");
}
where the callback function is anonymously inline, anything else doesn’t work. In my attempt to get a better understanding of the concept I decided to implement a sort of custom arr.reduce method and this was what I came up with:
function reduceArr(arr, addThem)
{
return addThem(arr);
}
let arr = [1, 2];
let total = reduceArr(arr, function()
{
let total = 0;
for (let i = 0; i < arr.length; i++)
{
total += arr[i];
}
return total;
});
console.log(total);
which works (though for some reason returns 3 and undefined) but when I tried to change the callback to a named function, I came up with this mess:
function reduceArr(arr, callback)
{
callback(arr);
}
function addThem(arr)
{
let total = 0;
for (let index = 0; index < arr.length; index++)
{
total += arr[index];
}
return total;
}
let arr = [1, 2];
let firstTotal = reduceArr(arr, addThem(arr));
console.log(total);
let arr2 = [1, 2, 3, 5, 8, 13];
let secondTotal = reduceArr(arr2, addThem(arr2));
console.log(total);
which just keeps on returning callback is not a function
when addThem returns total to line 3.
Phew! Sorry for the rambling.
Please can someone explain this thing to me in a non-jQuery/AJAX/Node way and also how to use named callback functions?
Thanks
EDIT:
What’s the difference between:
function callback(arg)
{
// stuff happens
}
function someFunc(arg, callback)
{
return callback(arg); // I'm hoping this is correct
}
and:
function anotherFunc(anotherArg)
{
// do something
}
function someFunc(arg)
{
return anotherFunc(arg);
}