How to Understand Callbacks & Higher Order Functions (FULL VIDEO Parts 1-4)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to this video on callbacks and higher-order functions these are core principles of the functional programming paradigm in JavaScript and these functions like map filter reduce I use every day in professional development environments and what we're going to do in this talk is we're going to go deep in understanding how to build those functions out from scratch in order that we develop an intuition of how they work so we can write them better debug them better and deploy them better in our own professional development careers I recommend you to take a look at our first video on the principles of JavaScript the execution context the memory the global variable environment the call stack in order to be sure that you have those foundations down because we're going to be making use of that understanding in this video but then come join us here and we'll get started on pull backs and higher-order functions we're going to begin with a metaphor I hate metaphors but we're going to begin with borderline I'm very impartial agnostic no ambivalent ambivalent or metric on metaphors by here is one that we are going to examine a function that is going to seem so useless then we're going to realize why we have functions at all and then why we might have these grand higher-order functions to profound higher-order of a greater order than regular functions I'm going to see why we have them we're going to see how I have them very soon first we're gonna create function 10 squared it's gonna feeling to be useful I'm certain of it Louis told me through the syntax once the wording not even declare totally exact wording of this function 10 squared we're going to define a function of 10 squared okay it's no parameter okay I'm just going to write this up return 10 times 10 okay function 10 squared no parameters there are no inputs exactly in the body of the function it will return 10 by 10 okay this is a useful function no no no it's a profoundly useless function Eliseo and it is profound Lee users function I call it and it returns 100 in literally in there is no variability what can do I can't reuse it in some other way I can't pull it and return 80 or 81 for a better example I can't reuse it in any other way it just evaluates 100 to 150 the number 100 well if you like this function you love my next function is e tell me how to create a function 9 squared how do I create function 9 squared declare a function call 9 squared and then we turn right that's annoying okay very good see excellent skyla creamy function 105 squares is more hard more challenging so you declare variable U path to the error function no give me a simple give me a simple punch 105 squared declare a function hundred and five squared no parameters in the body you would sure now okay these are not useful functions these are not useful functions right function nine square returns 81 8 squared 64 105 squared who knows we have we have a problem we're building brand new functions for every single number everything piece of data but every one of these functions has something in common what could we do just multiply me by myself a bit I am I'm multiplying something by myself and every single function has that in common and yeah I'm building out an entire new function for each number 9 square a square hundred it says something we could do differently here Louis you can add a second parameter that seeks a second parameter yes there's no parameters does any parameter well any yeah narrator ammeter know you could generalize it you could generalize watch what has Lewis says add like adding a parameter we could generalize our function and create something square num and then leave a blank number for later when we call square num fill that blank in with an actual value ten nine eight 105 whatever we can say square num is our general definition of how this functionality will work where is taking some input and multiplying it by itself and then don't determine the specific number we're applying that functionality to until we call invoke do we run that functionality and leave it generic leave it general when we define it so we can reuse it as many times as possible for 10 to make it live 10 squared 9 to make it live nights where 8 may like a square and this principle of making our functions reusable so that I can take the functionality multiply me myself and reuse it again and again for different numbers or different data that principle is going to turn out to be the essence and knowledge ously of why we have our higher-order functions it may turn out as not just some data we don't want to determine until we run the function some number but actually there may even be some functionality we don't want to determine we want to be specific on until we end up running the function it's going to solve this function here copy array and x to a function that's going to take in some list of data 1 2 3 4 5 6 and whatever and then it's going to take each of those numbers having created a brand new empty array and take each of those numbers double the modelling by 2 double and push them to that new array so we end up with a brand new array with each of those input numbers in the pretty an input array we've got a brand new array releases input numbers doubled in that new array copy array copy array and multiplied by 2 let's say this function is very useful taking some input data and doing something to it we do this all the time but we're going to discover man this and future of function is going to feel very repetitive we're going to feel in our gut to understand why we have a different approach a better approach but here we go starting off with here copy ray and multiply by two let's walk through it line by line starting off with our friend Louis what are we doing in the very first line of code Louis we're declaring a function array x 2 and we're storing it in both whenever X thank you this copy array copy array and x 2 and the whole function definition and remember as a little box like this and represents the entire function definition pilot console.log copy array x 2 i would see the entire functions description function copy or a month or two parens array whatever it might be the whole thing because it's all sort of memory all right z next line of code with declaring a variable claw my array in the quantized okay my race toward a global memory excellent with the values 1 2 3 next line Phillip we declare a variable results results in the global memory and we are going to be setting it to undefined right now do we run the function which function copy array North Delhi P array I'm going to keep me going for them so I'm gonna run copy or a and x to pass in my array which is a 1 2 3 yeah perfect that's been right indirectly I know the return value the output whatever gets returned from this one cool gets returned from it is gonna be sword in what for that result in a result perfect alright so we're calling a function how do I know importing a function so I you give the open parentheses there the all-powerful symbols in JavaScript they say go take my code and run it and anything that you declare inside it's stored in a memory in a memory what's that combined known as an execution context storing stuff in memory and going through the code line by line bundled up together is known as an execution context here it is fantastic there it is and into it we go now we can also keep track of these execution contexts or a school stack we may have always do so rigorously but here it is globe new in global to start with and we started calling copy ray x to so we add it to our call stack a stack of function functions being called being invoked and we're now inside copy room of our - its top of our call stack all right first thing we do inside for them we declared the parameter my array we problems right array okay perfect parameters array and we set it equal to the array one two three you know the value of the argument that's my array which is the value one two three perfect next line see we declare a local variable but set it equal to it good vocal very well put there it is emptier a perfect excellent thank you very busy next I see next time we run the for-loop aha okay mr. reinitialize before loop and it's gonna take this array one two three I'm gonna put it on the left-hand side which is slightly contravening our thread this being a thread of execution was as a workspace to talk about manipulating array rather than doing on the right-hand side here so when we hit the body the for loop I think about talking through for loop execution line by line not I loop through the array and it's kind of a but literally I hit the body good for loop the zeros time when I is zero what happens Tom easy we push we push the first element of the array okay so we take the zeroth element 1 is 0 so array sub 0 array index 0 is what value it's one it is one that we multiply it by 2 and that gets pushed into top perfect we take the one we multiply it by 2 we get 2 and we push that to output excellent array position zero is a number one because it's from my array which is passed in and filled in right position 0 is number 1 array index 0 array sub 0 always thing we grab that one multiply where do we get to and we push it to output perfect all right now it's full loop so Lewis one's next now we're increasing I by one perfect so I know one yep is less than your ring somehow the index of one is equal to the value of to find that by two and are pushing it toward a very good so good number for which we push the opera it's a four loop so we're gonna do again and get six four loops not finished alright because at this point when I is 2 we grabbed my RA position array position 2 which is 3 we multiplied by 2 years 6 we increment I one more time 2 3 now is 3 less than the length of your a 3 no it's not it's the same as so we skip out of the for loop and hit the final line of the function Louis which says what we're returning the array containing 2 person absolutely the value of output return output value 2 4 6 return it out into what global variable and to global memory the variable result perfect and we know to go back to global because we hit the return statement all that function copy or a moreover to meaning it got popped off the course at the call of that function was ended and look where do we go back to part 2 global alright when we returned out the 2 4 6 and stored it in the global variable result and a goal a goal of input 1 to 3 array returning out from copy or a model to a brand new array containing those input values doubled 2 4 6 we have been successful okay let's our funds on this function you lost me I'm clear I have some clarification questions everyone stands out everyone sums are no clarification questions or I'd fair enough well if you like this function you will love my next function this next beautiful function very nice very nice function copyright more point to his next function is very different very different function copy ray and / - look at this Radek radically do radically different we're gonna go through it though to feel just how different it is and there may be more than look just like this we're gonna feel this pain because with this cousin understanding of why there might be a better way so here we go copier a this time of the divine each other one by two not multiplying by two would divide by two like what I'm gonna write that again I was going to raise the bits to change just so we know just how little it is changing so 9 1 9 1 Z what are we doing we are declaring a new function called copy array / - excellent exercise lessons correct copy ray and / - EXO next line Z declares is Jack the global variable my array setting equal to a brave element 1 2 3 very good realize and then we declare their global variable result yep and we're setting it on the fine until we invoke the function okay so off we go and vote the function copier and divide by to invoke with the parens that means run the function what do we do at that point Z we create a new local context new estrogen context there it is context and we set the parameter array to 1 to 3 of it we set output to empty array empty array and now we get the one followed where we grab Phillip what when we first hit the boiler for new what is the value of I 0 I is 0 so raised sub-zero rained at 0 is what 1 1 so we take that one and do what with it / - and yet 0.5 naught 0.501 wait no wonder my no your smallest one nor point five is the British word for 0.5 it can tell you a funny story which I will not tell on video of the confusion that 0 and naught can cause do it anyway there we go normal 5 I want we do that 0.5 verb we push it to our output very perfect and I'll turn right now but right all right okay but it's a full loop it's a full loop so we're not done yet we get the body of it again this time the value of eyes and Walt Skyler is 1 is 1 which points to the value 2 okay is one which is position one is to retain that - then / - and get one one push that do I put it forward so we get the next one at one point five there we go nor point five one one point five and now we the close of our function the final line Louis which says what we're returning the output which is the array containing into our global memory which is the result a result global variable and look at that we have successfully run copy array divided by two which took him one two three and returned outlaw point five one and one point five this combination this function has served its purpose it has taken in an array and taken and turned out a brand new array with each of those input elements in the input array halfed okay we like this function imagine if there were another function okay function this function very different to copyright more poverty rate if I were to bring we're in a three recover in a three and convert a brand new function for it no not all right well principle are we breaking Z well present we breaking by building out each of these functions do not repeat the dry principle right don't repeat yourself we're breaking it profoundly everything's the same copy array and x - crate and taking an array create new output array loop through the input a rating gentlemen do something to it the only thing that changes is what is that what does anything with the changes go as the functionality that to the to the individual element the operator and the operand that little young individual thing the functionality we do to the individual element and yet we're building out entire new functions pop here and multiply with you going to vibrant we're in our three we're all that functionality building that's changing is a little thing with doing to the individual element fill it can you think of a better way of doing this can you think of a different if we think back to our function 10 square 9 square a square a hundred and five is there a better way you can see of rather than building a brand new phone could we do you know we can generalize it more we can generate and how would I do that you say to make it make it reusable but about how because I can't just go about like passing well tell me give me more details give it another parameter another parameter so so you're saying build one general function we gonna call it copier air manipulate and then leave a police hold a parameter for when we run that function fill that plate on that parameter in with a specific functionality plus 3 divided by 2 multiplied by 2 that we want to have applied to each element okay but how do we pass I think we just pass in when we include just passed in you know plus three like that to apply it inside is that legit no chance we can't imagine language could but in jobs will be definitely can't as passed little bits of functionality around and leave plates on it I've been wanting to leave a placeholder and pass in the plus 3 when we run copy array and do something manipulate let's say but we can't do it how do we wrap up functionalities we pass around in JavaScript Z in the car in the car back more intuitively in a function into sin function yes you're right he's right it's a Z phocion the only way I can pass punctuality around in JavaScript would be to get rid of the plus three and actually pass in an evil place all at for some functionality represented as a function and that's what we're going to do that is exactly what we're gonna do we can generalize have function that we pass in a specific instruction only when we run the query run when we run the copy array and manipulate so we can build a brand new function called copy real manipulate and when we call that function we run that function when we invoke that function at that point we can pass in the specific functionality but we're going to represent that with this instructions so just like a ray becomes 1 2 3 when we run copy or a manipulate so two instructions is going to become x 2 we're going to end up with x 2 grabbing the individual element of the array as an input 2 x 2 taking the you know array position 0 which is 1 and throwing it into x 0 and returning out to achieving the same as when we had arepas ition 0 number 1 x 2 we can't pass in x 2 we can do is pass in some functionality and then have the array position 0 and the number 1 thrown in to that functionality and then return that is we sort of flip it on its head to only a placeholder so that we can just have one copy around manipulate function and then have a placeholder not only for our data to be filled in with actual data 1 2 3 but also for some of our functionality we're gonna have some of our functionality in this case the thing we do to the individual element also left unknown never blank until we run copy array and manipulate and at that point we'll figure out what's instructions gonna be fulfill what's going to be all right we're gonna walk through this very precisely line by line so we truly understand it this is the last of our callback and higher-order function code here we go so 91 Skyler what are we doing in line one so we declared a function copy Raymond Avilla with the parameters arranged option copy array copy array and manipulate copy array and manipulate he's a whole of function definition sort of memory but we're not done yet z what's our next line of code say to do we declare the fashion x x 2 and it's a little baby function a little tiny function already gonna take in a single element hopefully so there at x 2 so we have a big function popular a little baby fun - more power - excellent next liners we're declaring a variable called result all right letting able to undefined until we invoke half period until we get the return I would say rather do we invoke even as we were voting it's gonna be undefined until we get the return value from the call to copy array and copy array and the manipulation and this function is taking in what as its first argument newest first argument is an array containing 1 2 3 okay perfect and the second argument Luis is is the function definition of x - ah the whole function definition of x - huh - it's the whole function which grabbing the whole thing so just like inside this copy row manipulate array is going to array is going to be replaced by one two three we have you seen array inside the body of this function no longer it's gonna say one two three jobs are going to replace it throw a pull out and replace it with one two three similarly wherever you see in word instructions inside of there javascript is going to grab out those instruction placeholder and say ah it's going to replace the whole word instructions with the words x 2 because 1 2 3 is filled in array and x 2 is filled in instructions as wherever you see instructions inside of this function it's going to be switched out for x 2 meaning we're gonna see something like x 2 parens while proper to being run with the input of array position 0 1 x 2 input 1 we're gonna get there in a second ok so we're calling a function copy around manipulate we know its output it's going to be stored in the global variable result but we've now got to execute this function so well together we create a new execution cards very in sync very good excellent all right new excision context very important thing to remember and say in chorus good so into it we go and it has a local memory and our thread when's its way in okay into the local memory we will be storing first our parameters and arguments or parameters was there associated value of the arguments Susie what's the first thing that goes in the local memory the first parameter is array it depends already yeah and that's fine through the array want to very perfect all right and the next one Phillip is gonna be instructions aha if we set the value of x to perfect the function definition of multiplied with the previously how the name or probably two it's just the function definition if this whole function definition previously known as x - not inside of here it was known as x - inside of here now we're gonna refer to its instruction so so to be clear for it if I wanted to run the functionality for me no more a tube from out here inside a copy of a a what enabled could I use for it oh these instructions instructions and I know and so far as a run x tune with the infinite reward I write instructions parens three ah because this really is x - it's going to be switched on for javascript in it's mine and switched with x - with friends on the end okay perfect alright next line of code Louis declaring a variable you know perfect empty array output so we have outputs empty raid array is one arrays one two three and now we hit the all-important moment the body of the for loop okay I has the value of what the zero of time we hit the body of the for loop I has a value of what skyla zero zero perfect so as a value of zero to a raid array index zero is what for one one so we take that wand array index zero is going to be switched out for the value 1 one is instructions being switched out for the value of 4 x 2 so we've now got x two parens 1 so we've got to create what for them a new execution plan a new execution context for instructions really x two with the input of one we would have create a new execution context for it oh we need to keep track of these on our contacts and there's a copy array and manipulate we were currently in that but within that copy or a manipulating we're going to call instructions so it gets put on the very top of the call stack instructions with the input of 1 and that's what we are at the moment that's where we are at the moment ok and into it we go well we're really doing with run instructions is running multiple by two so I even of one is being thrown into instructions really multiply by two so what Lois is the first thing you know memory of these instructions to really just multiply by two so our primary input is going to be one perfect even puts we look to multiply by two and see what is that one being thrown in to replace input so we get input is 1 and then notice we're gonna return input times 2 which is 1 times 2 which is 2 and that's going to be returned to the execution context of copy array with a perfect return one layer out to execution Ponder's of copy really relates that is the same x 2 input of 1 that whole section of code is going to be switched out and replaced with the return value of running multiply over to a given of 1 which is 2 and so this whole portion here will be replaced by 2 the return value and that to gets pushed to the output array ok and this execution context Skylar what happens to it it goes away we pop it off but it's a full loop and so we go back inside the for loop and this time the value of I is what flipped one so array index 1 is what - and we do what would that - we pass that two instructions yeah we have two instructions which is really not that much it ok so we create a new execution context pop off the last one filter bit off but we quickly out back on another one instructions with two and we go and the first thing Philip in our local memory our parameter input is set to - to perfect we do two by two which evaluates for we return out that for which is the output of running instructions remember - you return out that four and store it push it through whatever the output array a perfect so our instructions really multiplied by two input two which is array at position now one which is number two - takes goes into x - really instructions reading 1 by 2 and that multiplied by 2 in front of 2 returns out four and that for that whole block the running of instructions the calling of it with the parens which is really more probably to being run the whole thing is switched out with a return value which is a number four and that 4 gets pushed to output but it's a followed go six two four six and now we hit the final line of the function Z what's a fine line of the function Santa do we turn output return the value of output which is two four six into the global variable result there it is two four six and we have achieved the exact thing we did with our copy array and multiply by two we've achieved these exact same thing but we create a brand new array a brand new functional copy array and manipulate and then we left blank what exactly were due to each individual element we left a placeholder for the specific instructions we were going to do and copy rare manipulate when we passed in 1 2 3 and the specific instruction x 2 can live dynamically create became copy array and x 2 so we took him 1 2 3 and returned out to 4 6 we achieve the same thing as copywriting what why - but we never specified in copyright manipulate this will do multiply each other one by two we left it blank what was going to happen to each individual element with its a placeholder for it and then threw in only when we ran copy array manipulate the specific instructions we're going to apply to each individual element so how is it's possible if you government language other than JavaScript the notion of passing in a little baby function into another function to be used inside that function is anathema to your standards to what you know all the language design where you know of how functions should work and yet here totally fine 35 for us to pass a function in as input to be used inside of copy room and if we pass into one front by two to be used under a new label instructions allowed us to make our function general because we could leave it blank Nima unspecified what instructions is going to be what's going to happen to each individual element for the enemy removing run copy remove eight how is it possible in JavaScript functions are what's called first-class objects that means they have all the properties of objects and not the kind of feel they have they are absolutely objects they want blueness property we'll see in a second but otherwise yeah absolutely just objects and we know we can pass objects in two functions no problem performing standard but we can also pass there four functions that are just objects into functions they can coexist with them you treated like any Java object they can be stored on variables that's why you see var x 2 equals and the definition of the function they can be stored as properties of other objects where there are as methods they can be passed as arguments inputs into functions and they can be returned has the return value here we returned an array which by the way in Java is also an object but they can be returned as the return value the function will be returned out as a return value from another function and we'll see soon that gives us beautiful concept in JavaScript known as closure functions have one special property that objects don't have what's the one thing they could have they can be invoked they can be invoked you can put parens I can't declare an object and then invoke it but functions despite being objects have the ability to be invoked to be called to be run and we're going to see that as consequences later on in our object-oriented programming or to come but for now is that question this most profound concept callbacks and higher-order functions around when I first encountered the functions of a higher order and is much profound concept we've seen it all we've seen everything there is to see so which of these then is our higher order function and which is our callback function one of these is a high order function one is our callback function Scylla which would you say is out higher-order function more the blood bank - because you're passing it in mmm Phillip copy a rare manipulate : Graham manipulate is our higher-order function and then the little baby function gets passed in the baby function gets passed in that's our callback function a higher-order function is the outer function that takes in a function all by the way any function that returns out any focus that takes in or it turns out a function that host function is our higher-order function it's of a higher-order if you can handle other functions being passed in and returned out and then the function we pass in x 2.is placeholders instructions but more function that's our callback function so cool bass heart functions they simplify ad code they keep it dry we no longer had to create copy array and add to about three copyright x - hue / - we built one general copy array and manipulate and it had a placeholder for the specific thing we were gonna do to the individual elements and we can pass in therefore x 2 as a function or add three years of functional / 2 as a function we can pass those in and I nice to have one general functional as was I think it was all the code was the same if you look back to copy array x to copyright / - copyright 3 all the function code was the same we had taken array create a new empty array called output to loop through the input array do something to each element return out the full new output array but all that code was the same the only thing that changed was what did we do to each element to leave a placeholder for that give a placeholder for that and then pass in that specific instruction to do to each element only when we call copy array and manipulate pass in the specific functionality to do the new element multiple times in the for loop only when we run copy array and manipulate past in that specific functionality known as our callback function so callbacks and high order functions simplify our code they keep it and dry do not don't repeat yourself and they do something even more powerful that we're going to see later on they let us on asynchronous code and all that is to come later on
Info
Channel: Codesmith
Views: 36,246
Rating: 4.9573336 out of 5
Keywords: callbacks, higher order functions, javascript, computer science, learn to code, learn javascript, coding, programming, web developer, web development, react, redux, node, think like an engineer, coding bootcamp, coding bootcamp la, coding bootcamp ny, software engineering, software engineering immersive, javascript functions, javascript objects, basic javascript, intro to coding, learn coding, objects and looping, javascript looping, introduction to coding
Id: viQz4nUUnpw
Channel Id: undefined
Length: 40min 3sec (2403 seconds)
Published: Mon Jun 11 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.