What is a callback function in JS?

Hi freeCodeCamp forum users. I already know how to define and use a function. For example:

function sayHelloWorld() {
    console.log("Hello World!");
}
sayHelloWorld();

But I don’t understand about a callback function, like this:

let myArray = ['apples', 'bananas'];
function printArray(arr) {
    for (var element of arr) {
        console.log(element);
    }
}
myArray.forEach(printArray);

What does a callback function mean? And how it works? :confused:

Please answer. :smile:

Thanks!
Pummarin :smile:

MDN’s definition.

For this case printArray is the callback function- the forEach method calls it for you on every item of the array.

You may also want to look into higher-order functions (forEach is a higher-order function).

This is a bit on the pedantic side but it’s actually valuable to new learners to get this hammered home.