DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Updated on

Javascript: Callback

"I will call back later!"

Callback is a function passed as an argument to another function

This technique allows a function to call another function. A callback function can run after another function has finished

function myFunction( text, callback ) {

    console.log( text )

    /* --- */

    /* 
        call callback function
    */
    callback( 'text from myDisplayer (as callback function)' )  

}

function myDisplayer( text ) {

    console.log( text ) 

}

/*
    call myFunction
    myDisplayer passed into myFunction as an argument function
*/
myFunction( 'text from myFunction', myDisplayer )

/* --- */

// text from myFunction
// text from myDisplayer (as callback function)
Enter fullscreen mode Exit fullscreen mode

Example

Note

When you pass a function as an argument, remember not to use parenthesis.

Right: myFunction( 'text from myFunction', myDisplayer )

Wrong: myFunction( 'text from myFunction', myDisplayer() )


Waiting for a file

Top comments (0)