JavaScript Functions Crash Course
Key Takeaways
This video covers the fundamentals of JavaScript functions, including function declarations, executions, parameters, arguments, return statements, and closures, with a focus on practical examples and coding exercises.
Full Transcript
in this course you will learn all about JavaScript functions as one of the foundational pillars of programming understanding functions is crucial for every aspiring developer this course will provide you a comprehensive overview of functions in JavaScript breaking down complex Concepts into digestible modules from the essentials of what functions are and why they're indispensable to diving deep into terminologies Scopes closures and advanced patterns like higher order functions and recursion this video will help you become an expert at functions Tapas has over 18 years of coding experience and has a passion for teaching and creating open source communities he's the teacher of this course so let's get started Hello friends how are you doing what is this crash course about the crash course is about JavaScript functions so we'll be going through a bunch of details about JavaScript functions in and out and try to understand with lots of code like how it works fundamentally one thing I keep saying folks is that the concept is much much bigger than the syntaxes while we'll be writing code but we want to deep down in the concept first and then complete that with the syntaxes I hope you enjoy this entire course and if you so please like and share this video if you have any doubts comment below I am going to respond to you with all the doubts clarifications be assured about that okay so a few things before you get started how to take this course this is a longer video because of course it's a crash course we I have to fit in a lot of stuff within one video but if you follow certain patterns you will be enjoying the entire journey of going through each and every topic that we are discussing in this video okay so first thing take breaks don't try to consume all the content at once take adequate breaks and then try to feel like what you have learned are just few seconds back second thing after every logical chapter within this course try to understand whether you have completely got the concept or not if not go back and try to relearn no problem anytime go and try to relearn I will be teaching lot of exercises so you have to do this exercise with me but don't type them as I am teaching okay first try to understand what I am teaching try to completely get it in into yourself and after that pause the video try to do this you know those those code part by yourself all the code examples are already there on GitHub and the link to that is there in the comment section but in the description section of this video you can anytime pull it up and try to see like you know what is the code look like so no worries about that but don't type the code as I am teaching because then you won't be focusing on what I am teaching rather focus on learning and then try the code out so go repeat come back learn and everything and in case there is nothing clear feel free to comment I am going to respond to you look without any further delay let us get started [Music] foreign let's quickly talk about the concepts we'll be covering in this crash course so first thing we'll be talking about JavaScript functions fundamentals what is function what is it used about a very very basic level right I'm considering a beginner when they watch this crash course they will be able to understand what functions are and why they are used then we'll be clarifying few terminologies there are few terminologies which are a bit confusing when you learn functions for example functions versus methods parameters versus arguments and there are many more such terminologies that we want to clarify next we want to talk about function declarations we'll be talking about function executions then we'll get into call stack we'll talk about Arrow function nested function function scope we'll talk about closure we'll talk about callback functions higher order functions pure functions we'll talk about iifv we'll talk about recursion so there are lots lots lots to learn there are lots to talk about that's that's why I told you like when we go to each of this chapter in this course try to understand one chapter before you go to the next one and please practice the chapter before you go to the next one alright so take your time and let's get started with the learning the first one about JavaScript functions and its fundamentals so what is Javascript function before I get there let me tell you a story is the story of two frames one of the frame actually trying to cook a dish but she doesn't know the recipe of how to cook it so she called her friend who is sitting abroad over phone try to ask for the recipe for the friend at the other end she received the call and told the recipe line by line saying that hey if you want to cook this dish you have to follow this recipe like you have to put this first then you have to put this one then you have to cook it for so long and then finally your dish is ready great the friend cook the dish following the recipe that she got but after a week when she tried to cook it again she felt like okay let me ring up my friend again and try to ask the recipe and the same thing happened the friend gave the recipe over phone she followed the instruction cook the favorite dish next month the story remains same she calls up the friend again again got the recipe cook the dish for few months it went on like that but after that even though they are very best friend the friend who is sitting abroad really got frustrated of it and just told hey I have been telling you this recipe for like four or five months now why don't you write it down somewhere so that you don't have to ask me again and again and I don't have to perform this task of telling you again and again rather wherever you are writing it you probably can fetch it from there then what the friend did she wrote the every instruction in a diary and next time onward she never rang up the friend abroad rather followed it from the diary JavaScript functions a little bit like that so it saves you from repeating the same task again and again rather you put the task somewhere and then reuse that every time you have to perform the same similarly to that friend's story who wanted to create cook the dish but finally actually instead of giving the task of her friend to tell it again and again repeatedly she fetched it from the diary the friend never had to perform the task again okay so with this analogy in mind like reducing the task performing the task again and again rather we will create something so that we can actually reuse it whenever required in our programming that's the very very fundamental aspect of functions now you'll be getting into a graphics through which the similar kind of story we'll be putting into the code in a visual way and try to understand what exactly function does programming the yellow box you see in the screen consider that is a program and in that you have bunch of lines of code now just look at it a little bit closely there is a color coding there are a bunch of black lines then there is a green line again bunch of black lines there is a red orange blue again bunch of black lines and then there is a white line right so what do you try to mean here those black lines are the kind of code the same code has been repeated multiple times so three black lines then some other code then again same three black lines have been repeated then some other code then again three black lines got repeated like that right so there is a repetition exist now we want to bring in the concept of JavaScript JavaScript functions here so that we can reduce this repetition so what we do basically in this case you know going forward is we first Mark what are those lines that is that are getting repeated so you see here we have marked those lines that are getting repeated and the next thing that we do is like how can we make this code better so that we don't repeat the same task write the same lines rather than that we kind of take those lines somewhere give it a name in this case the name is like if you win fun and then what you do is like the same code that we got change it in such a way that instead of those line we are going to use the same entity the fun we had created before so do you see this one the number of lines of code has reduced drastically so what we did instead of repeating the same task in your code the first one we have now put the code in something which we call as function given it a name called if you win fun and then use that if you and fun in our code instead of repeating those lines every time so we are not only reducing the number of lines of code in you know in our total source code but what we are also doing is basically we are reusing something again and again now think about a case like why why do we need it the best case probably is let's say there is a problem in these three lines there is a bug in these three lines so in the previous case if there is a bug and you have to fix that bug or you have to fix that issue you have to fix this issue at least three times so you have to fix it in the first branch of line then again the second bunch of lines then again in the third bunch of line but as we have put this thing into a function in a single place and then reusing the same with its name in the multiple different places if you have to fix the bug now you have to fix it in one place just inside that function's body just inside that function and then rest of it will work so functions are a bunch of blocks that you keep together to perform something which otherwise will be very very repeated in your code function should ideally have a name but it can be without a name also in most of the cases you will have function with a name so that you can call the function with that name so you me every human being has a name and the purpose of the name is like we will be called by that name and when someone will call us by that name we'll respond and say hey I am here I am I am the person similarly for the function when we call the function by the name function we'll say like hey I am here and inside this I have this bunch of code go ahead and execute this code okay so that's the beauty of JavaScript function I hope you understood it I know these graphics and please keep it in your brain because you know the rest of the crash course we are going to use this terminology again and again you know for better understanding in programming at times terminologies are much more harder than the programming itself and when a developer gets stuck on those terminologies they feel so discouraged of learning that particular programming language it happens so that's where where you are learning any programming language or an aspect of a programming language you have to make sure that we understand certain terminologies very well when you are learning JavaScript functions there are few terminologies that you also need to know and you have to differentiate between them very well so some of the terminologies are functions and methods what are the differences we are going to talk about that then declaration and definitions what is the difference is there a difference between them arguments and parameters we'll be talking about that as well and then call back and hire other functions they will get confused often with these two so we'll be talking that also deep down when you go in the course itself so these terminologies keep in your mind like when we are talking about it make sure that in new head this terminologies and the differences or the similarities is completely chalked out completely clear if not go back and try to see like where I have explained this one if you still have further questions ask them in your comment section I'll get back to you [Music] let us now start creating functions and try to learn like how do we create functions okay as a thing before that so you can use any editor like you can use Visual Studio code or any other editor of your choice while coding what I am using right now I am using browsers depth tools and the console tab so that I can write the program here and execute them then and there so if you want any other mechanism like you will be writing on Visual Studio code and use the live server to run your program most welcome or you can actually practice them on the browser's dev tool just go press f2l open the dev tools go to console Tab and start writing your program and execute it because you're just practicing at this point of time so first first thing first what we'll be doing now is we'll be creating functions so we told that function is something which is going to help you to keep a bunch of instruction and code in a place so that you can reuse it again and again when you need it now to declare or to define a function so our first terminology Bank declaration versus definition so these two things are exactly same when it comes to function function declaration function definitions defining a function is kind of same so if somebody is saying I'm declaring a function or another person saying I'm defining a function they are actually talking about the same thing which is nothing but creating a function with bunch of logic so what we are going to do now we are first going to create a function so to do that I have to use a keyword called function this is the keyword and then I have to give the function a name I told just now the function may or may not have a name but most of the time the function will have a name so that we can call the function by its name just like the human being has name there are situations where the function may not have a name and we'll talk about the situations in the in in some time in this course okay so let's first give a name let's give a name called print me and then you know curly braces and then close that Curly braces so this is what you have declared or you have defined a function okay so right now the function has a keyword a name a bunch of parenthesis and then curly braces open a curly braces n inside this curly braces you are going to write every logic that you want this function to have so that you can reuse this logic anywhere you want so for example this particular function may just log certain thing into this console so you do console.log console.log console is like an you know something that you already have uh with JavaScript on this particular debugger so that you can use it for your coding purpose for your debugging purpose and on Console you have varieties of methods one of the method is log through which you can log something in the console so that you know you can actually read them or it's more for the debugging purpose that you can use okay so let us do something like printing something like this okay so I have created a function with a function keyword and the name called print me and the instruction the function has is a log that I want to print in the console and that logs is printing that's it so this is my function definition or function declaration now as I have declared this function with the name the next thing that I can do beautifully is by calling this function so to call this function just type the name of the function you know print me over here there is autocomplete already and then to call it you have to give this parenthesis otherwise you are just printing this particular function's name and if you just do this the function is going to print its complete body itself so if you just do print me the name itself it is going to give you a string version of the entire functions definition or Declaration that you have done just now but to execute to call it specifically you have to give this parenthesis you must give this parenthesis and then you press enter it will give its output it's just log printing because that's exactly what we asked this particular function to do so our function has worked that's great now as the function has worked um I want to just do something more with this okay so this is where what I am going to introduce something called parameter okay so let's write the same function function and we will say the name is print this and we will pass something over here which we call as parameter I'll get into it in a minute and then I'll close this functions body and inside this what I'm going to do I am going to write like console DOT log param so what does it what what does it mean what what I have done here okay so I have first similarly created a function with the function keyword and the function name here I have not done anything between these two parentheses but in this case I have done something in the parenthesis so whatever you put inside this parenthesis of a function it's called parameters okay whatever you put inside this parenthesis as called parameters you can put as many parameters that you wish to as long as you need in your programming logic so if I am passing param is going to just you know I can use this param anywhere inside this function so that I can do something with it so for example I can just now do print this and pass this is going to print the thing that I have just given over here so it means I can pass a value to a function and that value actually get mapped to the parameter and that's something that I can use you know inside the function to do anything that we want so again there is a thing that I want to call out over here there is a terminal logic thing a parameter versus argument anything in the function definition you pass inside this parenthesis is a parameter but when you call this function invoke this function the actual value that you are passing to this function is called argument okay so that's the difference sometime what happened that we call this also as parameter that I am passing the parameter we call this as an argument that I am passing the argument that's not the case so parameter is something that you pass to a function while declaring or defining the function which is like this but when you call invoke this function the actual value you pass to it it's called the arguments so I hope this is clear to you the parameter versus argument okay great so we have defined the function and we have now know what is parameter we have now what exactly is you know uh argument and and things like that okay so the next thing we have defined the function but there is one more way we can actually declare or Define the function that's called using the function Expressions okay so what is expression let's learn but before that let me just clear it off all this thing that I have done because I don't need it so if I say const count equals to 100. this is an expression what this expression has it has a variable name called count it has like you know how we have defined this variable we are saying this variable is a constant and then is a value of this particular variable okay so const count equals to 100 is an expression exactly similarly we can actually Define a function so let's take the print me function itself so print the print me function the print me is nothing but the function name which we can actually put as a variable over here and then what we can do here instead of that 100 value we can give function itself is a value and then we give the functions body and inside this function body we can give whatever we need sorry it's got executed my bad I'll just put it over here um you can give console Dot log say print right so this is what I have done so I have const print me equals to function and then this this thing so previously what I have done previously I have done this function print me okay and then I have done here console.log say printing so now I have just defined the function but I have defined the function in the function expression way so it means that the name that I have used for function before now it's a variable basically and then the variable what I have assigned is nothing but a function I have assigned that a function so it means print me is nothing but a function now when if I did const print me equals to 100 print p is nothing but a number which value is hundred now I have done cons print me equals to function that means print B is a function and then I should be able to execute this function so first I'll Define this okay print me has already declared because I have used this let's use some other name for now say print me again okay so this is the name and then I do print me again and I have to execute means I have to do this parenthesis and I got the print so this is another way I can actually Define and declare a function right now in the same thing in the print me again let's say print me again and let's say with param what I can do now I can actually put any parameter here right pair or I'll this time I'll put two parameters A and B and here after coming I'll be actually doing a and b I have done now declared it now let's say print me again with param if I do 10 and 20 as an argument is going to print 10 10 10 10 and 20. so I hope this is clear and now you know like how we can actually Define a function or declare a function there are two ways we have done okay so one is with expression another is without expression let's learn how to return from a function so return is something you will be using very often when you work with functions uh so far what we have done we have created a function but inside that we have just done a console.log statement which is not enough usually what happens is like when you create a function let's say function X and you have something over here right and then you will have say another function y okay and you have something over here and then each of these functions are supposed to do their own task right and in the entire program your entire application is not like that you will have only one function you will have multiple functions and what we'll be doing is like if function X whatever is supposed to do what you can use is basically you can use it like the output value of function X and take this into a variable like say late uh P equals to this and basically can use this P somewhere inside another function or anywhere else that in that matter so basically whatever the value of that X function that returns you can utilize that value anywhere else maybe in another function or anywhere in your programming right so that is that is that is very much a feasible thing in and the thing that you will be definitely doing now this thing to happen if you see this expression let me remove everything over here and just to put this for your consumption this this particular expression what we are doing we are having a variable called p and the piece value is what is not the function but the value we get from executing a function because we told a function name along with the parenthesis means executing calling invoking a function a function name without a parenthesis means it adjusts the string representation of the function definition itself this is a this is a difference that you have to keep in mind so in this case we have parenthesis means the function will execute function will be called or function will be invoked and within that if the function is returning any value if the function is returning any value that value will be assigned to this variable what if the function doesn't return any value here what if it just has a console.log like we have seen the function so far in that case simply the function execution will return something very special which is called undefined okay it means that something that is not defined yet is something called undefined okay so now let us create a function that returns something so for that we'll create a function say sum and we'll do a summation addition of two things so we will take a and b as two parameters terminology matters and what we'll do is like we'll do return of a plus b simple so it means that this is a function whose name is sum takes two parameters A and B it sum up those two parameter with this arithmetic operation and the result it returns you know back so let's execute sum it takes two arguments now let's put two and three so it means we are expecting a 5 is returning a 5. in the same method we can actually write little bit differently how so let's write the same method function sum we will do again a comma B and in this case we just did return of a plus b instead of that sometime you might want to do this also like late return a variable a plus b and then return that particular variable itself that is also same thing same as you know we have done whatever we have done before like returning a plus b directly right so if it is just a simple calculation returning it directly itself will be a shorter amount of code that people does so please follow that this is about returning returning from a function it means everything that you do inside a function all the tasks all the logic all the operations and at the end of it if you want the function to return a value so that that value can be utilized elsewhere you have to use the return statement followed by what you want to return I hope this is clear [Music] what is default parameter when you define a function we know how to define a function so let's define a function function will take the same okay a little bit different function let's say calc is a function and it takes a two parameters A and B and what we do we will return some value and the value that we want to return is something like 2 into a plus b okay this is the value we are planning to return so what does this function do a simple function a function whose name is calc takes two parameters A and B what it returns is for sum of these two parameters value then multiply it with 2 and then return something back a value back so let's execute this let's call this function with 2 comma 3 all right so what it gives you it gives you 10 yeah of course because 2 plus 3 is 5 5 into 2 is 10. similarly you can go do three into three what is going to give you 12 3 plus 3 is 6 into 2 is 12. now let's say someone in the team forgot to pass this second argument what you get you get not a number why do you get an order number because when you don't pass an argument for a parameter for the function the parameter value will be undefined we told about that so it means that in this case you are not passing the second argument so value basically so then B will be undefined now A Plus undefined and a will be 3 B is undefined 3 plus undefined is not a number of course it returns not a number now on a situation like this instead of getting not a number you might want to safeguard it with some kind of default value right some kind of default value of this parameters so that at least this one fail like this rather you can Safeguard them with some values of you know something that you are liking okay so what we are going to do the same function I'm going to bring in again and now I can actually default it to zero okay it's a default value or default value for this parameter that I am putting so it means if someone is not passing a value for this parameter using the argument s the value 0 will be used instead okay so let's do this now I am going to do calc 3 again if you see this now instead of n a n not a number it is actually retaining a value which is 6 which is let's do the computation a is 3 B is 0 3 plus 0 is 3 3 into 2 is 6 okay so you can do a default parameter value for your function if it is required to and in that case you can Safeguard it from an unnatural value return value from the function like not a number and you can actually override the undefined value instead of having undefined you can now set certain value with the default parameter [Music] rest parameters what is rest parameter so the rest parameter is something that allows a function to accept any number of arguments as an array any number of arguments okay now theory is one side let's do it with example let's create a function let's say give a function name will give a name call say collect things okay and we will have two parameters of it first is X and then is y now we are talking about rest parameters a different kind of special parameters right we know about default parameters now now we are learning about the rest parameters and I just now say the rest parameter allows a function to accept any number an infinite number of arguments as an array now to make sure the rest parameter accept an infinite number of arguments what we have to do you have to give a special syntax to it the syntax is with three dots so when we give three dots what happen is like this this particular parameter becomes rest parameter now here two things I want to call out a function definition can have only one rest parameter so it means that you cannot do X comma rest parameter y comma rest parameter Z you cannot do that so it can have only one rest parameter and the rest parameter must be the last parameter that you define for the function this two rules please keep in mind I'll repeat again a function definition can only have one rest parameter as we have over here with y the rest parameter must be the last parameter like how we have here so you cannot have like you know making this X as a rest parameter and then y as a normal parameter you cannot have that rather you have to have like this of course the name suggests it means rest means rest of it rest of it means whatever is left over so that is where it goes at the end okay now what I am going to do I am going to do a console DOT log of x and then I'll go do console.log of Y so that I can actually print and see like what exactly it prints now I have defined let's just do collect things sorry let's just do collect things and then pass some arguments any number five six seven eight nine okay nine enough now what I'm going to do I'm going to call collect things with nine arguments I can pass hundred thousands millions if I have time okay so let's test it with nine so what will happen the first argument that gets mapped to the first parameter so x value will be one and the rest of it 2 to 9 goes to the rest parameter so it means y will now accept from 2 to 9 but within an array okay so if I just printing it so if you see the first Sprints X is 1 and then rest of the eight goes inside an array two to nine this this subscript is a array notation two to nine and that that get assigned this enter array get assigned to this y parameter that's why it's called rest parameter hope it was again easy for you to understand and it will try to practice a lot about the rest parameter [Music] let's learn about Arrow function or fat Arrow syntax all right so we know how to define a function right let's do it again but this time let's repeat the one we did with function expression const add equals to of function and then we have two parameters over here and then we have return of X Plus Y and finally we close this particular breast so that works that's great right now what we can do over here to convert this one to a arrow function or fat Arrow syntax there are few adjustments that you have to do so initially the arrow function or the factors index looks little weird but how I try to kind of remember writing it and right now what happened is like I hardly write a function in the regular definition or Declaration way it's always about writing the function with the fat Arrow syntax or the arrow syntax okay so let's convert it if you're new to it you will take some time to get a grip on it but once you get a grip on it I'm sure that you are going to write the arrow function again and again because now I'm coming to the usage of it because the best uses you will write less number of code you will write lesser amount of code and be it any framework or any library today in the modern web development I think the diff Factor the very normal coding Syntax for function is using error function it doesn't mean that you cannot go with the traditional way of declaring and defining function or declare a different functions using expressions like the one we see on the screen you can always go with that but if you use add a function or you use fat Arrow syntax it's like you know much more modern is much more less code and of course there is one more thing that is there which I won't be covering in this crash course in the button the following one the relationship with the this keyword and arrow function Arrow functions no binding to this keyword that is what is another special case that comes but that will be covering into the this video that this keyword video that I'll be making next okay but let's now focus on how to convert this one to Arrow function okay so to convert this one what I have to do simple link one is I'm going to remove this function keyword so you don't need function keyword at all to make an arrow function next we are talking about this Arrow function so you need an arrow so arrow is a combination of this equal screen and this getter done so if you have a greater than and the equals and the greater than key without any space side by side you actually have an arrow like syntax and this is what is making is an arrow function so this is an arrow function Okay const add this is the parameter that we are taking and then what is happening basically I am having an arrow and then the definition of the function that's all about the error function so I'm not using the function keyword at all so let's just make sure that it runs 2 comma 3 it runs five okay very good but one more thing that I can do if the arrow function body the error functions declaration having only one statement just one line and one and and it's returning something you don't have to even give this you know curly braces so this one you can very well Define like you don't need this just get rid of it and then you get rid of it that's it so this syntax compared to this one you know the with the function keyword this is much much simpler isn't it so if you have a syntax like this it is it is way way easy for you and if it is something like you know you have dependency with just one parameter over here you don't have to give this parenthesis you can actually do things like this so if you have you know just one line stuff over here so it's much much simpler so this is the reason why a error function is very well you know appreciated sorry very well appreciated by the developer Community it is very well received by developer Community because you will be writing very less syntaxes very less code and in all the modern uh web development uh you know area data function is used very heavily so please practice writing Arrow function and I hope that you keep writing more and more error functions in your code than writing the function more traditional way thank you [Music] all right so nested function what does nesting means we know how to create a function let's say we create a function called outer and that function has a body and it can have certain instruction like what is this function supposed to do maybe in this case the function is supposed to print something called outer into the log now JavaScript allows you to create a function to define a function within within another function okay it might sound little bit strange if you're new to it but this is a very very powerful feature and this is the first basic thing towards understanding the concept of closure the concept of closure in functions in JavaScript function equals to the understanding of nested function plus function scope so if you want to understand closure deeply I want your attention over here first understand what nested function is how does it work up next we'll be talking about function scope and then we'll be talking about closure so that everything is very very clear to you and is very straightforward to you all right so nested function so function within a function this means I can create another function over here give it a name maybe for Simplicity I'm giving it an inner and I can give a console.log as I've defined this function using the outer function this function is called a nested function and this nested function as I have defined outside you know inside this outer function I have to call this one inside the outer function itself okay so like this so right now if I have defined it this way and if I call the outer function what will happen the outer function will be invoked it will print this console.log then it will see this inner function has been defined the definition happened and after that it will invoke the inner function also so what will be the output if I do this outer over here okay so the output is outer and then the inner so it first print the log outer and then the definition happen the inner get executed and this this inner actually gets print out so you can have nesting to any level in JavaScript functions however you won't see in practice uh you know too much level of nesting but you definitely will see now if you go back and see the code the various JavaScript code you will definitely will see some level of nesting some level of defining one function another inside another function happening and it's a very powerful feature we'll be able to see this in a moment okay [Music] just now we have seen what nested function is and now we are stepping into understanding function scope okay these two are a bit interrelated because you have to understand the concept of nested function you can define a function within another function and then the function scope is important to understand who can access what okay now there are certain generic rules but to understand those rules I thought a graphical picture will be much more important so please pay attention to this graphic over here so let's say there is a Javascript file you know and a function is defined inside that so the function is running globally it means that the function is not inside any other function so this blue one is a function this particular function is not inside any other function okay if the function is just defined globally now what happened there are there are actually two rules two primary rules that you have to keep in mind and these two rules are very important if you understand I want to understand closure okay so the first rule over here is variable that are defined inside a function the variable that are defined inside a function that cannot be accessed anywhere outside of the function okay so the variable that this one is defined inside this function cannot be accessed from anywhere outside of the function okay so anything defined in this blue box cannot be accessed outside of the blue box understood first principle okay a variable defined inside a function cannot be accessed anywhere outside of the function second principle the opposite of it a function can access all the variables inside the scope it is defined a function can access all the variable inside the scope it is defined so it means this blue function can access all the variables that is defined you know in the scope the function is defined in the global scope so inside the global scope if I am defining I am having any variable I will be able to access that from this function but the reverse is not true from the outside you cannot access the thing which is insight understood this to rule let's repeat this rule again because it's very important for us to kind of understand closure variables defined inside a function cannot be accessed anywhere outside of the function first rule second a function can access all the variables inside the scope that it is defined so this blue box is defined in the global Scopes in the global scope if there are any variables from this blue box the from the blue function I should be able to access it great now we have learned about nested function no so just replace This Global with a function and this function one with the nested function okay in our function so the global is outer function and this function is an inner function in this case also then the formula remains same the rule applicable over here also so it means your outer function cannot access anything from the inner function as the inner function is defined in this outer function so it means the inner function will be able to access anything that is defined in this outer function because inner function is defined in the outer function scope very simple right so now if it goes keep going nesting like in if there is another function inside is there is another function inside same rule applicable we have the same rule applied over there so this is how it works so you have to keep this thing in your mind now we are going to see with some code example here okay we'll be seeing some code example over here but you have to really remember this rule that a variable defined inside a function cannot access anywhere outside of the function you know from outside of the function a function can access all the variables inside the scope that it is defined so these arrows and these things if you give me keep it in your mind I think things will be very clear okay so let's move on and try to see like how the things Works code wise we'll be doing some coding now so based on the rules that we have learned so far we are going to write the code so that we understand this thing clearly right let's create a function let's create a function call say do something okay and what is this function doing it's basically um let's create a few variables inside that okay so let's do let x equals to 10 const y equals to 20 and then let const okay let's get VAR Z equals to 30 okay and then simply we'll do a console.log of X comma y comma Z okay so we know if I now to do something I just call this function I know what will be the output is 10 20 30 very very uh straightforward things that we have created over here okay so but this is where our rule number one comes into the picture what was the rule number one variable define inside of function cannot be accessed from outside right so it means I have defined let X const Y VAR Z inside the do something function and I've executed to something it's executed this console.log XYZ now if I try to take this console.log and try to execute outside what is going to happen do you see that it says X is not defined okay X is not defined maybe X is late so is not able to define y also is constantable how about the VAR no even if it is VAR and it is defined within a function you cannot access this variable outside a scope outside of this function you cannot access that is the first principle that we have learned just now right now second principle what was the second principle do you remember the second principle was about uh if the function basically now can access anything and everything from its scope basically the scope where it is defined to okay so let's see the second rule now what we'll be doing we'll be defining VAR x equals to 10 advanced y equals to 20 late Z equals to 30 okay now if I do uh function do something and do a console DOT log of x comma y comma Z what do you think will happen if I just execute do something what will happen do you think it is going to give an error or is going to print is going to print successfully why because our second rule say wherever the function whatever the scope the function is defined in that scope if there are variables declared the function can access this variable this function is declared in the global scope it means that function is not inside another function so it means if the global scope is having any variables so the function will be able to access those variables inside the function itself but when we did the thing other way around we have declared all this thing inside the function and tried to access them from outside it doesn't work so these two rules Define the functional scope the scope that we are talking about is the functional scope you have to remember what is accessible where simple thing if it is in the outer scope if it is if it is defined in the same scope where the function is defined it is accessible within the function but if it is defined within the function it is not accessible from outside even if it is a VAR that is declared and defined inside the function clear about it great foreign [Music] so ask a developer about a complex JavaScript topic there are higher chances that you'll hear back closures this is because the closures are not understood fundamentally by connecting the dots okay from connecting the dots point of view if you don't know about connecting the dots and creating a mind map to learn a complex topic I have created a video on how to learn JavaScript by connecting the dots please go ahead and take a look now coming back to closures if you learn closures by connecting the dots you will find closures understanding much easy if you just jump into closure and trying to understand you may not understand it well but if you come from the background of nested function then function scope you will be able to understand closure very easily okay so let's get into understanding closures so that we can actually fill it it's easy take a look into this picture on your screen so there is a box inside that there is another box consider this one as an outer function and this one as an inner function we have learned about the nested function already right so let's give them a name for example I'll give them give the for this one as F1 as a function one or will I'll give it as a name say outer to be very sure that they're out this is outer and this one of course inner now I know if I Define a variable over here say a this variable is not accessible from outside but if I Define a variable over here say B this variable is accessible from inside the inner function so we have learned this in the nested function and the function scope very clearly okay now what is closure the nested function is a closure this inner function is nothing but a closure okay as simple as that so if anybody asks you a definition of closure you can tell this nested function is a closure now if you go for a bookish you know closure definition for example if you go to mdn and try to look for what is closure you will get a definition like a closure is a function that can have three variables together with an environment that can run that variable okay which means it the the environment means nothing but this inner function and the variable means every variable that is defined inside that inner function and there is an ability through which you will be able to run things which is in this inner function so this inner function is basically is a closure okay is it's it this is how we should be understanding closure now let me summarize the inner function can be accessed only from the statements in the outer function correct we'll see it in code also and the inner function from a closure it means the inner function can use the variables the arguments everything from the outer function while the outer function cannot use the arguments and the variable from the inner function we have seen with this one if we understand like what is closure the closure is nothing but the nested function because it provides an environment you know to the outer world so this nested function can leave you know longer the nested function can leave longer for execution and it can actually perform the the all the required operations right so let's write a function will give the name as outer and let's take a parameter of this one outer function and then let's take another function nested function which is like inner we will also take a parameter over here and what we can do here this is the beauty of it the inner function can access the outer functions variable and argument so I can do return X Plus Y correct inner function can access the outer functions argument or any variable that is declared inside outer function so I can do return X Plus y pretty well over here okay and then finally what I can do I can do return you know okay I am returning this inner function as well okay now since the inner function the inner function is which one this one forms the closure this is what is closure okay now what I can do basically I can call this outer function okay and specify the argument and then leverage both outer and inner together that's the advantage okay so let me see how can I do this I'll just press enter now first what I can do const outer return equals to outer let's give 10 what do you think will be returned over here this is this is this is the this is the most interesting part what will return so once we call this outer function outer function return nothing but a function which is like an inner function now when the function execution is over the call is over that function is over right that function is no word in the picture so if I in press an enter over here outer is just over it is nowhere in the picture but the beauty of it the beauty of it is the argument I have passed to Outer it still leaves where it still leaves inside inner because this stain was passed over here this stain is still used over here and it still leaves even after the outer execution because outer Returns the inner so inner is actually over here outer return so let me just if I just do outer return for you if I just do this one and print this for you what it returns is returns inner y return X Plus y so is written this function where X is nothing but this 10 that I have passed so though the execution of outer is over but the value that we have passed throughouter still leaves within inner so it means it means if I just execute Outer Outer return now o u t here outer return now with the parameter set 2 is going to give me the output of 12 why because outer return is nothing but this inner function inner function expects a parameter over here the parameter that I have passed as you know pass the argument over here but what it did it actually use this 2 with a variable that I have
Original Description
Learn about JavaScript functions in this full course for beginners. Functions are a fundamental building block of programming, and they're a great way to make your code more readable and maintainable.
✏️ Course developed by @tapasadhikary
We will cover the following:
✅ What and Why JavaScript Functions
✅ Clarifying Terminologies(function vs methods, parameter vs arguments, and many more!)
✅ Function Declarations
✅ Function Executions
✅ Default Parameter
✅ Rest Parameter
✅ Call Stack
✅ Arrow Function
✅ Nested Function
✅ Function Scope
✅ Closure
✅ Callback Function
✅ Higher-Order Function
✅ Pure Function
✅ IIFE
✅ Recursion
❤️ Try interactive JavaScript courses we love, right in your browser: https://scrimba.com/freeCodeCamp-JavaScript (Made possible by a grant from our friends at Scrimba)
⭐️ Contents ⭐️
(0:00:00) Welcome to JavaScript Function Crash Course
(0:01:52) How To Take This Course?
(0:03:10) What Are JavaScript Functions? Let Me Tell You a Story.
(0:07:04) Learn JavaScript Functions Visually.
(0:10:49) JavaScript Terminologies You Must Know
(0:12:02) How To Declare a Function?
(0:23:03) How To Return From a Function?
(0:27:14) Default Parameters For JavaScript Functions
(0:30:20) Rest Parameters For JavaScript Functions
(0:33:48) JavaScript Arrow Functions
(0:38:30) Nested Functions in JavaScript
(0:41:17) Understanding JavaScript Function Scope
(0:49:35) Mastering JavaScript Closure With Easy Guide
(0:59:27) What are Callback Functions in JavaScript?
(1:06:03) What are Higher Order Functions(HOF) in JavaScript?
(1:12:32) What is a Pure Function in JavaScript?
(1:16:34) What is an IIFE In JavaScript?
(1:21:30) Learn JavaScript Call Stack(Function Execution Stack)
(1:27:25) What is Recursion in JavaScript?
(1:35:16) Closing Notes and What's From Here?
🎉 Thanks to our Champion and Sponsor supporters:
👾 davthecoder
👾 jedi-or-sith
👾 南宮千影
👾 Agustín Kussrow
👾 Nattira Maneerat
👾 Heather Wcislo
👾 Serhiy Kalinets
👾 Justin Hual
👾 Otis Morgan
--
Learn
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from freeCodeCamp.org · freeCodeCamp.org · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
React: Production Server Setup Part 2 - Live Coding with Jesse
freeCodeCamp.org
cookies vs localStorage vs sessionStorage - Beau teaches JavaScript
freeCodeCamp.org
Browser history tutorial - Beau teaches JavaScript
freeCodeCamp.org
Graph Data Structure Intro (inc. adjacency list, adjacency matrix, incidence matrix)
freeCodeCamp.org
React: Parameterized Routing with Next.js - Live Coding with Jesse
freeCodeCamp.org
React: Dealing with jQuery Issues - Live Coding with Jesse
freeCodeCamp.org
setInterval and setTimeout: timing events - Beau teaches JavaScript
freeCodeCamp.org
Browser and Device Testing - Live Coding with Jesse
freeCodeCamp.org
Last Minute Updates - Live Coding with Jesse
freeCodeCamp.org
Post Launch Updates - Live Coding with Jesse
freeCodeCamp.org
React: Setting Up Google Analytics - Live Coding with Jesse
freeCodeCamp.org
React: Masonry Layout - Live Coding with Jesse
freeCodeCamp.org
Load Balancing Digital Ocean Droplets - Live Coding with Jesse
freeCodeCamp.org
try, catch, finally, throw - error handling in JavaScript
freeCodeCamp.org
Load Balancing: SSL Passthrough Setup - Live Coding with Jesse
freeCodeCamp.org
Graphs: breadth-first search - Beau teaches JavaScript
freeCodeCamp.org
React: Masonry Layout Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: WordPress API Live Search - Live Coding with Jesse
freeCodeCamp.org
Creating WordPress Custom Post Types - Live Coding With Jesse
freeCodeCamp.org
Dates - Beau teaches JavaScript
freeCodeCamp.org
Miscellaneous Front End Updates - Live Coding with Jesse
freeCodeCamp.org
Merging a Pull Request from GitHub - Live Coding with Jesse
freeCodeCamp.org
React + Prettier + Standard JS - Live Coding with Jesse
freeCodeCamp.org
React: Sortable Responsive Table - Live Coding with Jesse
freeCodeCamp.org
Geolocation Sorting by Distance - Live Coding with Jesse
freeCodeCamp.org
Tradeoff Matrix - Agile Software Development
freeCodeCamp.org
The Definition of Ready - Agile Software Development
freeCodeCamp.org
Getting first React job without experience - Ask Preethi
freeCodeCamp.org
React: Google Analytics Click Tracking - Live Coding with Jesse
freeCodeCamp.org
Submitting a PR to an Open Source Project - Live Coding with Jesse
freeCodeCamp.org
Should I go back to school to get CS degree? - Ask Preethi
freeCodeCamp.org
Hero Section CSS Changes - Live Coding with Jesse
freeCodeCamp.org
Working Agreement - Agile Software Development
freeCodeCamp.org
A day at Pennybox with Co-Founder Reji Eapen
freeCodeCamp.org
React: Sorting and Filtering Data - Live Coding with Jesse
freeCodeCamp.org
React: Sorting and Filtering Data Part 2 - Live Coding with Jesse
freeCodeCamp.org
React: Building a New UI - Live Coding with Jesse
freeCodeCamp.org
Definition of Done - Agile Software Development
freeCodeCamp.org
Getting started with jQuery (tutorial) - Beau teaches JavaScript
freeCodeCamp.org
Making a React Blog with WordPress Content - Live Coding with Jesse
freeCodeCamp.org
React, NextJS, CSS - Live Coding with Jesse
freeCodeCamp.org
jQuery events - Beau teaches JavaScript
freeCodeCamp.org
React/NextJS Routing and WordPress API Custom Types - Live Coding with Jesse
freeCodeCamp.org
React: Working with API Data - Live Coding with Jesse
freeCodeCamp.org
React: Refactoring Components - Live Streaming with Jesse
freeCodeCamp.org
jQuery effects - Beau teaches JavaScript
freeCodeCamp.org
More React Refactoring - Live Coding with Jesse
freeCodeCamp.org
animate in jQuery - Beau teaches JavaScript
freeCodeCamp.org
"Finishing" My React Site - Live Coding with Jesse
freeCodeCamp.org
Starting a New React Project (P2D1) - Live Coding with Jesse
freeCodeCamp.org
React Project 2 Day 2: Learning Material UI - Live Coding with Jesse
freeCodeCamp.org
The Agile Manifesto - Agile Software Development
freeCodeCamp.org
jQuery: get and set with http, text, val, and attr - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 3 - Live Coding with Jesse
freeCodeCamp.org
The INVEST approach to product backlog items
freeCodeCamp.org
React Project 2 Day 4 - Live Coding with Jesse
freeCodeCamp.org
Chickens and Pigs - Agile Software Development
freeCodeCamp.org
React Project 2 Day 5 - Live Coding with Jesse
freeCodeCamp.org
jQuery: add and remove DOM elements - Beau teaches JavaScript
freeCodeCamp.org
React Project 2 Day 6 - Live Coding with Jesse
freeCodeCamp.org
More on: Prompt Craft
View skill →Related Reads
📰
📰
📰
📰
The Minecraft anvil is a tree-cost optimization problem in disguise
Dev.to · Mark
KMP Algorithm (Knuth-Morris-Pratt): The Smart Way to Perform String Matching in O(N)
Dev.to · Jaspreet singh
Every Backtracking Problem Is the Same Three Lines. I Just Couldn't See the Tree.
Dev.to · Alex Mateo
DSA From Zero to Hero #3: Sliding Window (Fixed Size) Explained With a Java Example
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI