JavaScript Function - What's your Function?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Grossberg it's great to learn because knowledge is power functions are the backbone of JavaScript development yet also one of the most difficult concepts to master but once you understand functions everything else in the language becomes relatively easy we'll start from the absolute basics then go into practical examples of arrow functions closures higher-order functions recursion and we'll even talk about some common best practices for writing high-quality JavaScript code welcome to episode 4 of the full course JavaScript function if you're new here like and subscribe and you can follow the full free course on fire ship IO now in order to understand a function let's start by dissecting it and looking at its anatomy what we're looking at here is a function declaration also called a function definition or statement it starts with the function keyword then you need to choose a name for it and you should choose something that's readable to other human beings because there's a good saying there's only two hard things in computer science cache and validation naming things and off-by-one errors in other words choosing the right name for your function is almost as hard as making a joke about programming but once you decide on a name the next step is to add parentheses and then add any parameters or inputs to the function you can think of a parameter as a variable that this function lot access to when it's called and then from there we have curly braces and everything inside is the function body and that's where you define all your logic the function body will typically do one of two things it will either perform a task or return a value or possibly both an example of a function performing a task is a console log and because there's no return statement it will implicitly return undefined but a function body might also contain a return statement and that allows us to take the value that was calculated inside the function body and set it as a variable now at this point we've declared a function which describes what the code will do but in order to actually execute it we need to call the function we do that by referencing the function by its name and then we pass in actual values as arguments to the parameters so imagine you get asked on an interview what is the difference between a parameter and an argument you might say something like parameters are the variable inputs that you use in the function definition while arguments are the actual values or expressions used when calling the function so what we just looked at there was a named function declaration but there's also a thing called a function rushon which basically means using a function as a value let's go ahead and refactor our declaration to an expression we'll use the same function name but instead set it as a variable and then use an anonymous function which is just a function without a name as the value now when calling these functions they will produce an identical result and if you watch the previous video you might know that the function declaration is hoisted while the expression is not the function declaration will always be put at the top of the scope which means you can make calls to the function even if it's declared somewhere later in the code but when you have an expression the function doesn't actually get created until that code is reached in the script and that means you get an error if you try to call it beforehand so now that you know the difference between a function declaration and expression which one should you use well there's actually no universal best practice here but I think most people today would lean towards function expressions because they're not hoisted it makes it easier to understand where they belong in the context of an application and they're less likely to pollute the global namespace and speaking of that a cool thing you can do is create an immediately invoked function expression by wrapping an anonymous function in parentheses you can then call it immediately by adding parentheses afterwards but I think that looks goofy because what we're talking about is the whole invocation but we got these things hanging outside of it looking sort of like dog balls you know what's important is the whole invocation so I would put the parents around it that's better I think so now let's go ahead and switch gears and take a closer look at parameters and arguments as you can see here we have three parameters a main aside and a drink and if we want to log those out at runtime we can do console log arguments which is a keyword built into JavaScript this particular function takes three positional arguments and that means when you call this function you need to pass in your arguments in the right order that's pretty manageable when you have three arguments but imagine we had five or ten arguments to a function things to get out of hand very quickly but when you run into a situation like that a common solution is to use an object for named parameters the make lunch function only has one single argument but that argument is an object that can contain multiple values and that means we can D structure the object or use it directly inside the function body so with this approach you don't have to worry about the order of the arguments and also makes it more flexible to extend your code with non breaking changes in the future now one other trick that JavaScript has up its sleeve is rest parameters in the make dinner function we have a single parameter but it's preceded by three dots that allows us to call the function with multiple positioned arguments and then access them as an array inside the function body now at this point we've only been looking at the function keyword but there's actually a more compact and concise way to write your functions and that's using the arrow syntax let's go ahead and refactor one of our earlier function expressions to use the arrow syntax we start with a variable to provide a name then we have parentheses with the parameters to the function and then we have an arrow that points to the function body a cool thing about the syntax is that if you omit curly braces then it will implicitly return that value from the function and that means that three lines of code now become one now if you have additional work to do inside the function you can still add brackets in which case you would still need to add a return statement to return a value from it but arrow functions are more than just syntactic sugar there are a couple of other characteristics that you should know first of all they will always be expressions and that means you can't simply declare an arrow function in your code like this and the other big thing is that they don't have their own this object now we're not going to get into this in this video because there'll be an entire video dedicated to object oriented JavaScript that covers this and much more but here's a little history that you should know for right now prior to arrow functions every new function would have its own this context that was based on how that function was called and the reason this is important is because you might see older code where you have a function that defines a variable named self that is equal to this and the reason you see code like this is because JavaScript will close over that variable and allow you to reference it consistently and other functions for example if we define a property on this function we can now reference it using the self variable and other functions but the great thing about arrow functions is that we no longer need this ridiculousness we can just use an arrow function get rid of these self variable and we're good to go now that's more information than you need to get started working with arrow functions but it may come into play if you use a framework like view in particular so always make sure to read the instruction manual that comes with your framework and from here on out we'll be mostly using arrow functions because I think you should prefer that syntax when possible now another big thing you'll hear from thought leaders in the industry is the value of pure functions but what is it that makes a function pure well let's start by looking at an impure function first we have a global variable then we define our function and that function mutates the global variable and also uses it in its return value what makes this code difficult to work with is that its operating on values outside of its local scope and when you have functions that depend on and you take little variables it tends to create a lot of drama let me just explain to her what's going on you're gonna have it we're all clear yeah I just want to talk about what Garret because this is the most important thing this conversation wasn't even how all this guy brought up I was Manning up there then because Garret asked me and I left the house there Steven got back to my one-on-one both both you told me who could make sure you don't talk about any of us so a pure function is one that only depends on its input parameters and only mutates variables within its local scope and it should also not produce any side effects and the end result is code that will always produce the same output given these same inputs code like that tends to be easier to test and also just easier to think about in general not to mention pure functions will help you compose your applications as a collection of higher-order functions we learned in the very first video of this course that JavaScript supports first-class functions and that means that you can pass functions as arguments to other functions or use functions as the return value from a function so when you hear the term higher-order function or higher-order component and react we're simply talking about functions that take other functions as input arguments or return a new function when they're called using a function as an argument is a very common thing to do in JavaScript especially when you start working with async code we're not going to cover async stuff in this video like promises and callbacks because that deserves an entire video on its own but a simple example of a higher-order function is the set timeout function that's built into JavaScript it allows you to execute code after a specific delay and it achieves this by taking a function as its first argument and then the number of seconds that you want to delay as the second argument we don't want to immediately execute the function that we pass to the set timeout instead we wait for the delay and then the JavaScript engine will call that function later hence the name callback function and you'll see code like this all over the place in modern JavaScript another thing we can do with functional code is replace traditional for loops as you can see in this example we are looping over an array and then we're mutating each item in that array with a new value but in modern JavaScript we can achieve the same thing in a single line with array map which takes a function with a specific signature as its argument and it will call this function for each item in the array so X represents an individual item in the array and then the return value from the function is what we want to transform it to and this is especially awesome when combined with arrow functions because you can achieve a lot with a single line of code and if you want to reuse this code you can simply set up a function expression with a descriptive name and then pass it as the argument to map now I should point out that these functional techniques tend to be less performant than a regular for loop so I feel obligated to mention that even though it's not going to matter in the majority of use cases now another type of higher-order function is one that returns a function now the thing you should know at this point is that whenever you define a function you're also creating a lexical environment and that sounds like a pretty scary term but basically anything inside of curly braces is its own lexical environment now the inner function has a lexical environment that contains its own local variables and also a reference to the outer environment which includes the outer function as well as the global script as well basically what this boils down to is that the inner function can remember the local variables in the outer function but the outer function can't look inward at the local variables in the inner function as we can see here from the undefined error now let's go ahead and define a function called use cat that is a closure loosely inspired by react Oaks the outer function is its own lexical environment and will define local variables within it such as a default name when this function is first called then we'll return an array that itself contains two different functions the first one just gets the name and prefixes it with meow well the second function is a setter that takes a new name as an argument and then sets it as the name in the outer function and now we can use it in a way that resembles use state from react to X but the most important takeaway here is that the inner lexical environment or the inner functions in the array have access to the local variables in the outer used cat function so I highly recommend that you practice this and get comfortable with closures because you'll find them on both interview questions and in the real world and speaking of interview questions another thing you might encounter is recursion in JavaScript we can create a recursive function by simply defining a function and then calling it by name in the function body when this function encounters the function call it's simply going to push another instance of this function on the call stack and in our case we have no stopping condition which means it will do this forever in an infinite loop until we reach Stack Overflow let's go ahead and look at a more practical example using nodejs that will traverse the filesystem on this computer recursive algorithms tend to be very efficient when traversing tree like data structures in nodejs we can import file system which is a module that will allow us to read files on this local system and we'll define a function called traverse that takes a directory path as its argument from there we'll use node to ensure that this path is a directory and then we'll read the contents of that directory that will give us an array of subfolders or it will be undefined so by adding a conditional statement we've added a stopping condition to this recursive function because if no subfolders exists then it will stop rehearsing or stop looping over that function call but if we do have subfolders then we'll go ahead and loop over them with the for each method and then we'll call the outer function that we're defining right now by name and that's the thing that gives us a recursive function and lastly we'll start the whole process by calling traverse with the current working directory now at this point we've covered a bunch of different ways to use JavaScript functions but the best way to fully understand these concepts is to get a lot of practice and that's exactly what we'll be doing in the upcoming videos in this series so if this video helped you please like it and consider becoming a pro member at fire ship IO thanks for watching and I will talk to you soon [Music]
Info
Channel: Fireship
Views: 93,216
Rating: undefined out of 5
Keywords: webdev, app development, lesson, tutorial, higher order functions, js, javascript, js functions, that weird js course, nodejs, js function, js tutorial, javascript tutorial, learn javascript, iife, arrow functions, computer science, cs, functional programming, functional code
Id: gigtS_5KOqo
Channel Id: undefined
Length: 12min 26sec (746 seconds)
Published: Tue Aug 06 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.