DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on • Edited on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay