• Home
  • About
  • Contact
Brandon Tillman

Callbacks | Understanding JavaScript flow

March 9, 2016 by Brandon Leave a Comment

Callbacks

Understanding callbacks is essential, they not only provide a means to application flow, but allow you to write cleaner, and more modular code too. You must understand that functions are first class citizens in JavaScript, they can be stored in variables, passed into functions, and returned as a result of an operation. Using a callback is simple, all you need to do is supply an argument into a function, that you will pass data and “call upon” to return that data to the calling function. Sounds complicated, but I promise you its not, have a look at this:

function sayHello(callback) {
    callback("Hello");
};

sayHello(function(greeting) {
   console.log(greeting + ", World!"); 
});

// Output: Hello, World!

As you can see, I’m passing an anonymous function into the callback of my sayHello() function, and greeting gets populated with the callback.

Lets take this example a little further, I’m going to add the ability to say hello in different languages by passing the language in as a parameter, along with the callback.

function sayHello(language, callback) {
    var greetings = {
        "English": "Hello",
        "French" : "Bonjour",
        "German" : "Guten Tag"
    };
    // Return the greeting
    callback(greetings[language]);
};

sayHello("German", function(greeting){
   console.log(greeting + ", World!"); 
});

// Output: Guten Tag, World!

Once again, I invoke our sayHello() function, and pass it an anonymous function, expecting a greeting. However, this time I first pass the language string, to be used as the key in the greetings object. I then callback with the value of the property, which sends the correct greeting back.

Another Example

Have a look at the code below, it creates an object with two callback methods. At the bottom, we invoke those methods and pass those results to a logger function. This example demonstrates how useful callbacks can be, in a more app like structure.

    var callback_examples = {
        // Calls back with a number that is 1-100
        get_randomNumber: function(callback) {
            var randomNumber = Math.floor((Math.random() * 100) + 1);
            // Returns randomNumber to the anonymous function
            callback(randomNumber);
        },
        // Calls back with a name via index
        get_nameByIndex: function(index, callback) {
            var names = [
                "Foo",
                "Bar",
                "Mr.Callback"
            ]
            // Returns the name to the anonymous function
            callback(names[index]);
        }
    };
    
    // Helper function to log the results
    function logResult(functionName, result) {
        console.log("The result of %s is: %s", functionName, result);  
    };
    
    // Call our functions
    callback_examples.get_randomNumber(function(num) { // <-- Anonymous function with the callback
        logResult("get_randomNumber", num);
    });
    
    callback_examples.get_nameByIndex(2, function(name){ // <-- Index along with anonymous function
        logResult("get_nameByIndex", name);
    });

I’ve gone ahead and created a Gist on Github for the code callbacks. Feel free to comment there or below, let me know if you have any questions, or if I misspoke (I’m learning too)!

Link to callbacks Gist here.

  • Author
  • Recent Posts
Brandon
Sr. Software Engineer at Undisclosed Investment firm/Brokerage
Latest posts by Brandon (see all)
  • RadListView | Using the Telerik UI for Xamarin.Forms - August 6, 2019
  • Clean Architecture | Creating Maintainable Software using .NET Core - May 2, 2019
  • Xamarin Forms How-to: Navigation with slide out menu - August 15, 2017

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to email a link to a friend (Opens in new window)
  • Click to print (Opens in new window)

Like this:

Like Loading...

Related

Posted in: Featured, Javascript Tagged: Callbacks, JavaScript, Tutorial
← AngularJs Tutorial: WoW Realm Status
ASP.NET Core Identity | Change default password restrictions →

  • Popular
  • Latest
  • Today Week Month All
  • Xamarin Forms How-to: Navigation with slide out menu Xamarin Forms How-to: Navigation with slide out menu (14,759 views)
  • Clean Architecture | Creating Maintainable Software using .NET Core Clean Architecture | Creating Maintainable Software using .NET Core (4,810 views)
  • How to: Create custom code snippets in Visual Studio Code How to: Create custom code snippets in Visual Studio Code (2,123 views)
  • AngularJs Tutorial: WoW Realm Status AngularJs Tutorial: WoW Realm Status (1,374 view)
  • Entity Framework Code-First tutorial | C# .NET MVC 5 Entity Framework Code-First tutorial | C# .NET MVC 5 (1,032 view)
  • RadListView | Using the Telerik UI for Xamarin.Forms RadListView | Using the Telerik UI for Xamarin.Forms
  • Clean Architecture | Creating Maintainable Software using .NET Core Clean Architecture | Creating Maintainable Software using .NET Core
  • Xamarin Forms How-to: Navigation with slide out menu Xamarin Forms How-to: Navigation with slide out menu
  • How to: Create custom code snippets in Visual Studio Code How to: Create custom code snippets in Visual Studio Code
  • password ASP.NET Core Identity | Change default password restrictions
Ajax spinner

Beer me!

Did one of my posts help you out? I'm glad! If you'd like to help supply my fuel for more posts - please consider donating to the cause!

10-Day Free Trial

Tags

.net .Net Core AngularJS API Architecture Authentication Blizzard API Callbacks CentOS code first commanline entity framework HTML5 http JavaScript linux minecraft Networking restful srv Telerik Template Tutorial UI vm VSCode Web web api web development Webservice wordpress Xamarin XAML

Recent Comments

  • Tillman32 on Xamarin Forms How-to: Navigation with slide out menu
  • hartman on Xamarin Forms How-to: Navigation with slide out menu
  • Tillman32 on Xamarin Forms How-to: Navigation with slide out menu
  • hartman on Xamarin Forms How-to: Navigation with slide out menu

Categories

  • .Net
  • AngularJs
  • Entity Framework
  • Featured
  • Javascript
  • Linux
  • Minecraft
  • Projects
  • Tutorial
  • Videos
  • Wordpress
  • Xamarin

Follow me on Twitter

My Tweets

Copyright © 2023 Brandon Tillman.

Omega WordPress Theme by ThemeHall

%d bloggers like this: