Understanding JavaScript Callbacks

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
callbacks are central to asynchronous coding in JavaScript in this tutorial we will examine callbacks and depth if you haven't used callbacks then most of the coding you've done in JavaScript is executed all at once sequentially as the program runs this is synchronous however there are many times when it is beneficial to have code executes after something else has happened not sequential we call this asynchronous callbacks allow us to achieve this and it is necessary to solve many programming problems now a callback is simply a function that is invoked or called after something else happens so whether or not the function runs depends entirely on something else happening not simply the running of the program this is achieved in JavaScript by passing a function into another function and then the function that we passed in is called back executed after something else has occurred this is possible because JavaScript supports higher-order functions if you need to review the concept of higher-order functions I will include a link in a description for this video let's look at a couple examples to see how this works in the first example we are going to look at a function that is called after a certain amount of time set timeout allows us to do that so first I'm going to set up a function and all this function is going to do is just log to the console we'll keep it simple so we have our function and then as I said set timeout is a function in JavaScript that allows us to execute something after a certain length of time and it uses a callback so here's how it works set timeout and then we pass in the callback so in this case I'm passing in the function that I created and then we indicate how long it is to wait now I'm going to say 3 seconds so that's basically all there is to it this here is the callback this function will not execute until after something else has happened and that something else is 3 seconds so let me save that let me open the console and then refresh this page and we'll go ahead and take a look at it so there I've refreshed the page three seconds later we get the console log statement so after 3 seconds it called back this function now in this example I define the function here before passing it into the set timeout function down here in JavaScript you can define the function at the time you pass it to the function this is called an anonymous function and it is really the standard way of doing this type of thing in JavaScript so let me show you that so instead of passing a function that's already been defined I simply define it at the time I pass it in like this I'm gonna do the same thing have the text just a little bit different so right here is the function definition and it's an anonymous function and it's not assigned to a variable it's simply a function expression that's included as we are calling the set timeout function and then we still have the other parameter which indicates three seconds this is a time expressed in milliseconds so three thousand would be three seconds so let me go ahead and remove this and we'll try this again save it come out and refresh after three seconds we get the function was called back so there's our first example of a callback where a function is passed into another function then after something happens that function is called invoked now a very common application of callbacks in JavaScript are event listeners you don't want something to happen until an event occurs for example clicking on a button so you pass a function to an event listener when that event occurs it calls back the function so let's take a look at that I'm going to use this HTML page here which has a button as a part of it and let me go ahead and delete this and now let me grab the button first I'm going to use query selector to grab that button and I will simply pass in the ID now we have the button we can set up the event listener and the event that we want this to fire before is click and so we indicate the event now here is where we pass in the callback once again I'm going to define the function right here now I am entering a parameter e in case I want to do something with the event object I won't in this example that's usually what I would do if I were creating an event listener and we'll just have it log to the console in this simple as that so the callback is right here and that function gets called back whenever a click event happens on this button so that is a callback let me go ahead and save that I'm gonna copy file path for this HTML file so we can take a look at that here's the button if I click it the button was clicked so when I click it the function is called invoked and we get the message all right now sometimes you may choose to create your own callback so so far we've been using some functions available in JavaScript that accept callbacks as a parameter well you may want to create a function that's like that as well let's look at an example I'm gonna copy and pasting in here let me describe it so I have an array sit up here and this array consists of multiple objects basically each object has a name a score and a school so let me give you the for instance for this example that I'm going to do let's say we have a lot of data and the data spans more than one school it's data about students and basically it for our simple scenario here it has a name and a score now I'm only ever concerned about one of those schools and that happens to be East okay so that's the school I'm concerned about I never want to deal with any of the other data and so since I'm constantly doing stuff with the data that is provided with the students array I created myself a little function and here's the function process students now what this function does is it cycles through the array and simply checks to see if the school is east so we simply look at the data the school attribute we convert it to lowercase and then we check to see if it's equal to East if it's equal to East then I've decided well I want to do something with it now what is it that I do with that data well I want this function to be reusable I want to be able to use it a lot and so if I hard-coded what I wanted to do with it I would use it in one case wouldn't be able to use it in another case and so what I decided to do instead is set it up so I could pass a callback a callback function into it and then right here I check to see if that callback is a function using type of I want to make sure it's a function but before I try to call it or invoke it then right here is where I invoke it and I pass in the data whatever data I'm working on so it will only pass in those that have a school of east it won't pass in anything that's West so this is a function I've created that uses a callback yes it's a simple scenario but what it does is it illustrates how you may want to create functions that use callbacks on your own now let's go ahead and see how we could use this so first example let's say I want to process the students so I'm going to pass in the students array and here's where I'm going to pass in my callback function and what I want to do with it is I simply want to print to the console I'm going to keep it simple I want to print to the console whether the student passed or not so here's my function I use a parameter obj because notice the callback has the data passed in and so I have to be able to grab that and what am I going to do with that I'm simply going to check to see if obj dot score is greater than 60 if it's greater than 60 then I'm going to consider that they passed now if I wanted to do a different number than 60 at some point obviously I could and I wouldn't have to change this function at all simply the function I pass in would be different so let me finish this off obj name passed all right so that's my first example let's go ahead and see how that works I'm going to save that refresh it here we get Mary passed james passed Rachel passed and Lynette passed now if we jump back and take a look at the data Mary is with east James is with East they're both above 60 Steve is with East but he wasn't shown because he's below 60 60 or below Gabe is with West Rachel is with east and she's above 60 Rochelle is with West Lynette is with East and above 60 as well and so those are the four that it printed out now to show how flexible this can be let me do one more thing I'm going to set up a function that's going to compute the total of all the scores together for East and also account so how many students are in our in East I could then use that number to figure out an average or other things but that's that's what I'm planning to do so I'm gonna create a second function I'm gonna call a determine total now I'm going to set up a couple of variables first first variable is for the total and then I'm going to set up a count variable as well and initialize those to zero let me scroll this up so it's a little bit easier to see all right now I have those two set up I'm going to call process students and once again I'm gonna pass in the students array and here is the function this is my callback function and now I'm going to do something different I still use the parameter obj so I can accept what is passed in the object that has passed in but here's what I'm going to do total equals total plus obj score now this will automatically get all of the east students because process students is already doing that for me and then I simply count to increment my count all right just so we can see what we get let me log to the console at the end of this function total score will log out total and then we'll also log out count so there's a log statement all right so I have my function set up now just going to call it down here so we can see what we got let me go ahead and save that refresh we have the same names from the other one but now notice we get total score 390 and total count 5 so if we jump back to the data 1 2 3 4 5 there are 5 and East and if you add those up that does equal the total we receive which is 390 so just an example of creating your own function that uses a callback now we also did something interesting in this to determine total function here I use closure so that I could keep track of a total and keep track of a count without creating a global variable if you're interested in learning more about those concepts I'll also leave a link to tutorials for those concepts in the description section of this video now if you found this video helpful please give it a like and if you'd like to continue learning here are some suggestions first you can click the video link in the center to access another tutorial right away if you haven't subscribed to the channel click the circle link on the left I release a new tutorial each week and if you are ready to dive into a full course click the link on the right to visit my website all things JavaScript comm thanks for watching
Info
Channel: All Things JavaScript, LLC
Views: 112,837
Rating: undefined out of 5
Keywords: javascript, tutorial, javascript tutorial, javascript fundamentals, javascript instruction, training, learning, all things javascript, callbacks, asynchronous
Id: Nau-iEEgEoM
Channel Id: undefined
Length: 15min 39sec (939 seconds)
Published: Wed Nov 01 2017
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.