pjk_ok
pjk_ok

Reputation: 967

Callback function is not executing

I'm learning about callback functions, and I have this code where I pass the initial function in as a parameter, into the final function.

I can't seem to work out why this isn't woking? It's supposed to turn the body element red, and also log the variable 'body' to the console.

let body = document.querySelector('body');

function callbackFunction() {
body.style.background = "red";
}

function anotherFunction(callback) {
console.log(body);
}

anotherFunction(callbackFunction);

Upvotes: 0

Views: 101

Answers (1)

Mitya
Mitya

Reputation: 34598

Well the passed callback is never executed.

function anotherFunction(callback) { //<-- callback received
    console.log(body);
                                     //<-- ...but never executed
}

Just add an invocation:

function anotherFunction(callback) {
    console.log(body);
    callback(); //<-- call the callback
}

Upvotes: 4

Related Questions