JS Arrow Functions: Everything You Need to Know

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
everyone it's cold today we're gonna talk about everything you need to know around javascript arrow functions arrow functions are incredibly useful they can make your code a lot more concise there are lots of variations and how you can write them lots of different pieces of syntax as well as a couple of gotchas you need to look out for that's what we're going to talk about here if you haven't checked out my new software engineering bootcamp take a look it's online it's self-paced there's a job guarantee if you don't get a job in six months you don't pay a cent you work with a mentor some of our mentors are from companies like uber or Google I just talked to a student this morning had a long meeting with him who is working with a mentor from LinkedIn he meets with them every single week and gets feedback on his code ask questions so if you're at all interested in changing careers or learning web development and you want to do it online that having to quit your job and you want the security of a job guarantee take a look at the link in the description you can apply you can learn more you can talk to someone on the phone and now the advertisement is over let's get back to arrow functions as you know most likely if you've worked with JavaScript JavaScript is a very function heavy language functions are really the one concept if you had to pick one the one concept that you absolutely must understand be able to work within write in order to be a JavaScript developer we write a lot of functions we pass functions all the time as callbacks we're writing asynchronous code where we have functions it's just a fundamental part of JavaScript and for a long time every time we wanted to write a function we use the function keyword here is a function called divide yes there's some small differences right we could have a anonymous function I can have a named function so I could have done function divided like that but I'm still using the function keyword at the end of the day and that can get kind of lengthy this isn't bad but if I have some code like this where I'm using different array methods like filter and reduce and I'm passing in an anonymous function that exists solely for the purpose of being an argument to filter or reduce it's kind of a lot of characters to have to type a function so this is where arrow functions come in arrow functions are a syntactically compact alternative to a regular function expression so what that really means is they are shorter they're a shorter way of writing a function and that's really the main benefit most of the time is just that they're shorter they're more compact but there's also some situations where they do behave differently from a traditional function expression and that can be an advantage it also can be something you need to look out for so we'll cover that towards the end of this video before we go into the actual syntax notice this right here the poor internet explorer logo being crossed out if you head over to mdn scroll down to the bottom of the arrow functions page look at our browser support table that's a lot of red for IE but that's pretty standard for IE as well so just be aware arrow functions are newer they're pretty well supported but just not in IE alright so with that said let's take a look at these syntax so the name arrow function is two five from the arrow that we use when we're declaring an arrow function equal sign greater than so here are two examples of arrow functions one thing that you need to know right away is that arrow functions can only be anonymous functions we cannot name an arrow function yes we can store it in a variable just like we can store a regular anonymous function expression but we can't name it like I showed just a moment ago function divide that is a named function if we have an arrow function it's always anonymous follows this pattern so parentheses and arrow curly braces now some of this is optional sometimes and if I want to be able to call this function later and reuse it I'll store it in a variable so I'll just call this one Const how about we just rewrite what we have right there divide so divide equals and this part is replacing this right here so I have my arguments between those parentheses and then the function body between curly braces and I'll just return X divided by Y and I can call it just like any other function divide 1/4 0.25 the next thing you should know is that those parentheses right here around x and y are optional if you only have a single argument so if I had a function called square Const square equals I could do this where I have X my arrow and then I can return x times X but those parentheses are not mandatory in this one scenario so square of three is nine I can leave them off for some people this is a stylistic thing certain lenders will enforce that you do have those parentheses and others will enforce that you don't but they are not mandatory as far as the language is concerned but if we had two arguments like we do for divide it's not going to be happy with me so we do need those parentheses there and if we have no arguments if I want to have a function or call it annoying I still need those parentheses we just leave them empty and we'll console dot log lol oMG hey we can call annoying just like any other function lol oMG hey so parenthesis arrow and then curly braces however that's actually not always the case what's really nice about arrow functions is that there are situations where we can leave off the curly braces we can leave off the return and they can become even more compact so let me show you an example here I have a function called is even it takes some number in and it returns whether that number is even or not we mod by two and see if the remainder is zero that should be a true or false value we've returned it so here is one version with an arrow function kind of like what we've already been doing num arrow return num mod two equals zero here is another version numb without the parentheses because we don't need them arrow returned num mod two equals zero here's a third version where I'm using parentheses instead of curly braces so those parentheses allow me to write a single expression that will automatically be returned so I don't need the return keyword so why don't we rewrite square just put it down here comment out these others get rid of those curly braces replace it with parentheses and get rid of the return and the semicolon whatever expression is inside of these parentheses will be automatically returned so I don't write return it's an implicit return if I call square of nine we get 81 so this is looking shorter definitely than what we had before we could do the same thing for divide so let's move that one down here divided X Y and instead of returning X divided by Y I could put parentheses here and just have the expression X divided by Y and that will be returned but it gets even shorter if we want it to I don't need those parentheses for something so simple something that's short it can fit on one line I can just rewrite it like this so X divided by Y is the return value now this is really nice but it's only worth doing if you have a short enough expression you don't want something that goes on for like 30 40 50 100 characters on a single line even if technically you can fit a single line there in addition there are some rules you have to have a single expression if you want to use the implicit return so you cannot have let's say an if statement in here if X is greater than zero we'll return x times X that's not going to work else whatever if I try running this it's gonna get very confused syntax error unexpected token if it's not expecting any sort of keywords like if in here it just wants a single expression so most of the time if you have a single expression it does fit on one line but you will see these parentheses often if you're working with react you'll often see arrow functions used to pass into map or filter or something where we have some arrow function and then we want to return a single expression it just happens to be a react component now if you don't know react this probably is meaningless let's say it's a profile component so that may not fit on a single line if you have a lot of stuff going on profile name equals blah blah blah age equals that would be tough to put on one line but it is a single value a single expression it will be automatically returned because of those parentheses but I could also have just done curly braces and explicitly return to this value to okay so if you don't know react don't worry about it let's check out divide our one-liner let's divide 7 by 8 0.875 so that's an example of a one-liner this is one of the really nice parts of using arrow functions one thing to look out for if you are ever writing an arrow function that returns some sort of objects literal like what's a good example here we'll just make something up how about const make card and this function should return an object that has a suit let's say suit is hearts and it has a value of 3 so this represents a card it just always returns this one card presumably there would be a reason for that it's an object and if I wrote this function exactly as it is right now and I tried to call it save my file we get a syntax error what's happening here is that the arrow function while javascript is confused by the syntax when it encounters curly braces it assumes that it's a function body so it thinks that our function looks like this it's looking for some valid line in a function body it's not treating it as an object literal so if you ever are trying to implicitly return something like this you're trying to implicitly return an object literal you need to wrap it in parenthesis and now JavaScript knows oh this is just a return value it's not actually the curly braces for a function body and now I can call make card it's useless but it does work so yes we can write arrow functions as standalone functions that we save in a variable like I've been doing but really where I end up using them the most is when I'm passing a function in as an argument somewhere which is a pretty common thing to do in JavaScript here I've got an array called invoices imagine I'm running a plumbing business and I'm keeping track of my clients and invoices for some reason with a JavaScript array we've got an array of objects a client name an amount that they owe and then whether they have paid or not so down here I'm creating a variable called still owed to figure out how much money I'm still owed at this point what are the outstanding invoices that have not been paid and I'm filtering based off of who has not paid not invoiced doubt has pay so that will give me an array with the three I think it is yeah three objects of three clients who have not paid has paid it's false and then I'm running reduce on that to sum all of those amounts together those three amounts and I end up with eight hundred and thirty dollars 83 cents so this is kind of a lot of syntax to do something pretty common and pretty simple so let's try writing an arrow function version still owed equals invoices and then I'll just drop down to the next line dot filter and then I'll use an arrow function so for invoice why don't we just call it I it's kind of cheating because that will make it shorter anyway but sure let's use I and then instead of doing curly braces and return I can just do a one-liner not I dot has paid that will automatically be returned true or false filter wants a callback that returns true or false so that should work for us let's take a look at still owed it is that array that's been filtered a new array with the three clients who still have to pay then I can add my dot reduce do it on one line as well and if you're not familiar with reduce I can't remember if I have a YouTube video on this or not if not I'll put one out shortly it can be kind of confusing but this isn't a video on reduce so we'll just run through it really quickly there are two arguments of this callback a total often called accumulator just call it total and then invoice will be each element in the array that we're reducing just call its I again and then I'm just going to return total plus invoice dot amount so total plus PI dot amount and then I pass in the initial value for reduce as zero so if you're not sure about reduce this is more about arrow functions anyway take a look at the difference here a significant difference let's try running this just save my code look at still owed and we get the exact same value so this is much much shorter much nicer to write over this especially when we're doing these one-off functions that we don't ever we can't even reuse so at this point really we've just been talking about arrow functions as a shorter or as mdn puts it more syntactically compact alternative which they clearly stole from my slide syntactically compact alternative but that's actually not the only difference between arrow functions and regular functions if we go back to mdn and we scroll down to this part right here that says no separate this this is the second important distinction between regular function expressions and arrow functions aside from them being shorter arrow functions do not get their own value of this like a regular function expression does so if you need to brush up on this here's a quick crash course the key word of this is going to change it's going to be set in a given function depending on how the function is called but with an arrow function the key word this is not going to change relative to the context of the parent that the function is defined it so for example if I had an object Const person and this person has a name the name is Bilbo and then I have a method and this method could be called say hi and I'll do a regular function expression and it's just going to console dot log this dot name so when I execute this function I'll call it like person I guess I shouldn't to just say this dot name I'll go with this dot name says hi okay when I call person dot say hi the value of this is going to be determined by how I'm calling it I'm calling say hi on person the object person will be the value of this this dot name should be Bilbo so when I run the code I get Bilbo says hi however if I used an arrow function instead just comment that out and I'll rewrite it as an arrow function like this and I try calling it again we just get says hi so what's going on here is that the value of this is not being changed it's not being set when I'm calling person dot say hi like a normal function would if we look at this console dot log this this is just set to the window object just as if this function were defined on its own not inside of this object and it doesn't matter how I call that function if it's an arrow function the value of this is not going to be set to this object unless I were to bind it or do something fancy but on its own an arrow function does not get a new or a different value for this here's another example where arrow functions could be problematic I have two different elements that I'm selecting on my HTML page I'm not showing it to you at the moment but there's a button and there's an h1 I'm selecting them both with query selector and I'm adding an event listener to both of them one is an h1 one is a button when you click on either we're calling make purple make purple is just a regular old function an on arrow function I've defined that sets this dot style dot background color to be purple this will be referring to whether it was the button that was clicked or the h1 that was clicked this will be set to that elements so if I open up the HTML and I take a look I'll click on the h1 it turns purple I click on the button it also turns purple if I were to rewrite make purple as an arrow function save it to a variable equals arrow function here and I'll print out this so you can see what's going on console dot log this same logic same this dot style dot background color equals purple so if I try clicking now click here click here we end up with two console out logs of the window object the global value of this we are not getting a new value for this inside of the arrow function like we would for a regular function so that can be a problem we do not want that behavior most of the time but there are situations where the lack of a new value for this can be useful here's an example I'll modify make purple for some reason I want it to have a 1 second delay before actually changing to purple so I want to click and then wait a second and then the background should turn purple and to do that I can use set timeout and I pass in a callback function in here then I'll pass in a time like 1000 milliseconds one second then I'll have call this code in that callback so we start that timeout and after one second then we changed this dot style dot background color to purple with a regular function an on arrow function this is actually problematic if we click we wait a second and we get an error cannot set property background color of undefined what happened here is that the value of this changed because I'm inside of yet another function and the way that that function was called was on the window set timeout is a window method so if I console dot log this I click after a second you'll see that this is the window but this right here is not the window so let's print out this first and then inside the set timeouts this starts as the button and it changes to the window really annoying it doesn't even look like this is on the window but it is this is a window method set timeouts so that's problematic and what we used to do before arrow functions what was pretty common was something like this Const that equals this so we would store the value of this up here before this callback function and then we would set that dot style dot background color now I'll click wait a second and it does turn purple but with arrow functions we can get around this entirely we don't need that instead we can use an arrow function right here as the callback and we will not get a different value of this the value of this will be the value that this was up here we're not getting a new value because it's an arrow function so I don't need to do that weird that two equals this I click we wait a second and it still works so we just saw that arrow functions behave differently with respect to the keyboard this that can be a drawback at times you don't want to use arrow functions for methods on an object but if you're cognizant of that it can be useful like in this situation where I don't have to bind or I don't have to save the old previous value of this I use an arrow function and I avoid that entirely and that's kind of it for arrow functions I don't know why I said kind of it we've covered a lot the syntax shorter more adorable especially when you can get a nice one-liner with an implicit return you don't need curly braces you don't have to write function you don't write return but remember arrow functions are always anonymous you cannot name them there are great especially as callbacks they don't get their own value of this and I think that's it as I do this little video end cap here's some footage of one of my cats so thank you for watching everyone if you're not subscribed already I just highly recommend it I can't recommend it enough you'll never regret it so please consider subscribing leave any comments especially if you have feedback or ideas for future videos and like the video all that stuff I really appreciate it have a great day and I'll be back next week
Info
Channel: Colt Steele
Views: 19,681
Rating: 4.963964 out of 5
Keywords:
Id: thXp0_py9X4
Channel Id: undefined
Length: 20min 22sec (1222 seconds)
Published: Thu Feb 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.