Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are javascript callbacks just anonymous functions sent as an argument in a function call?

Tags:

javascript

Are Javascript callbacks just anonymous functions sent as an argument in a function call?

For example,

mySandwich('ham', 'cheese', function() {  
   alert('Finished eating my sandwich.');  
  }); 
like image 727
Yetimwork Beyene Avatar asked Jan 28 '26 23:01

Yetimwork Beyene


2 Answers

JavaScript callbacks are functions passed as values into an asynchronous function for the purpose of continuation.

Functions are values:

So in JavaScript, you can pass a functions around like values. You can reference a function in a number of ways:

  1. Pass a literal anonymous function as the callback

    doSomeWork(function (err, result) {
        if (err) {
            throw new Error(err);
        } else {
            console.log(result);
        }
    });
    
  2. Pass a literal named function as the callback

    doSomeWork(function magicalCallback(err, result) {
        if (err) {
            throw new Error(err);
        } else {
            console.log(result);
        }
    });
    

    (Naming every function is a smart idea because you can see it in the stack trace)

  3. Pass in the value of a variable which happens to be storing a function as the callback

    var someFunction = function callItWhatYouWant(err, result) {
        if (err) {
            throw new Error(err);
        } else {
            console.log(result);
        }
    }
    
    // reference the callback stored in the someFunction variable
    doSomeWork(someFunction);
    
  4. Pass in the function by referencing the function name as the callback

    function callItWhatYouWant(err, result) {
        if (err) {
            throw new Error(err);
        } else {
            console.log(result);
        }
    }
    
    // reference the callback function using the function name
    doSomeWork(callItWhatYouWant);
    

Continuation?

Continuation is all about the next step. When you call a function which is asynchronous, it needs to notify you that it is done. The callback acts as the next step, i.e. the asynchronous function will call you back when it is done.

So a callback is just a function argument used for a particular purpose, that being, continuation.

Callback signature

There is no standard for which arguments a callback should take, but in the Node.js community we have adopted the general signature

function (err, result)

where err is an Error object if something bad happened, or null if things were successful. If things went bad result is generally undefined, otherwise it contains the result. So your callback is generally called by either

callback(new Error("oops"));

or

callback(null, result);

Also note that it's normal for the last parameter of an asynchronous function to be the callback parameter

function callLater(delay, args, callback) {
    setTimeout(function () {     
        callback(null, args);
    }, delay);
}
like image 182
Matt Esch Avatar answered Jan 31 '26 11:01

Matt Esch


In your example: yes

But in m example: No

function myCallback()
{
    alert('finished eating my sandwich');
}
mySandwich('ham','cheese', myCallback);

So, from you comment I think the real question is: What is an anonymous function? I did my best, but it is still early in the morning here, so don't shoot me.

Well, gooed question. Hard answer

when defining a function, it lives withing its scope. Scope? huh? Ok, let's start again.

when a webpage is loaded, the browser creates a window object. It then starts parsing everything you wrote in that document (let's assume HTML).

Every DOMElement it encounters, gets put into the window.document object. Every Element inside the widnow.document element is rendered/interpreted in your browser window.

Now, the browser encounters the following <script>:

var myVariable = 'So cool';

The browser sees var myVariable. This tells him to create a variable called myVariable in the current scope (again that word). the current scope is window (the window object the browser created). So it adds the variable to the window object:

window.myVariable === myVariable

The same goes for functions

function myAwesomeFunction()
{
    alert('I am so cool');
}

Creates a function inside the current scope (window) with the name myAwesomeFunction. So again:

window.myAwesomeFunction === myAwesomeFunction

But what if I want to create a function I don't whant any other code to have access to? What if I want a function that should only exist when a certain specific button is clicked.

Well, enter anonymous functions. these are functions that are declared in the anonymous scope. they cannot be accessed using the window object:

myButton = document.getElementById('myButton'); // === window.document.getElementById('myButton');
myButton.addEventListener('click', function()
{
    alert('I am so awesome');
});

Now, the function you passed into the eventlistener only lives inside the eventListener. It doesn't even have a name. So it's scope is 'the on click event of the button' but we can't access it from outside because it doesnt have a name. Thus, anonymous function.

A good read would be to google stuff like 'javascript scope', 'javascript window object', ... A lot of good articles give a better in depth explanation of all the words I threw at you.

like image 27
Pinoniq Avatar answered Jan 31 '26 12:01

Pinoniq