Search code examples
javascriptfunctionfor-loopcallbacktruthiness

Callback function with a truthy value in JavaScript


This is my very first post on StackOverflow, and I would be grateful if you could help me clarify, at a conceptual level, what's happening in the following JavaScript function. So, I've been practicing the language for a while, and I'm now diving a little deeper in the world of functions. Here is my dilemma:

function findEven(array, callback) {
    for (let i = 0; i < array.length; i++) {
        if (callback(array[i])) {
            console.log(array[i]);
        }
    }
}
function isEven(num) {
    return num % 2 === 0;
};
findEven([2, 4, 6, 7, 9, 12], isEven);

Now, I understand what this does, and I know that I could achieve the same result with a simple .forEach(). What I would like to get, though, is what the conditional if (callback(array[i])) is doing. Is it establishing if the callback function is truthy (as per the MDN glossary, all values are truthy unless they are defined as falsy)? And why is that, because I added the callback function, after defining it, in the final array? In fact, if I try to strip it off, it returns the error: "callback is not a function". Can you confirm that? I hope I posted my question in a meaningful way, thanks in advance!


Solution

  • The conditional callback(array[i]) verifies if the value of isEven() function passed as callback evaluates to true/false for array[i].

    function findEven(array, callback) {
        for (let i = 0; i < array.length; i++) {
            console.log(i, array[i], callback(array[i]));
            if (callback(array[i])) {
                console.log(array[i]);
            }
        }
    }
    function isEven(num) {
        return num % 2 === 0;
    };
    findEven([2, 4, 6, 7, 9, 12], isEven);

    If you print the console.log statement, you will see, for the values, callback() evaluates to true, gets printed in console. False value are ignored.