Javascript for Beginners - Functions Explained!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone how's it going welcome back to my JavaScript crash course for beginners series what I'm going to talk about today is JavaScript functions explained in a simple and easy to follow away specifically what I'll cover is what a function is how they're typically declared in JavaScript how and why you normally use functions and of course like always a bunch of examples as I go along in the code to make things super duper clear to everyone as you can see I'm using the same setup I always do we'll use the terminal window here to go launch the Python server I'll just go do that now let's go here and and there we go that'll just let us host the files and run this from the browser I've already got Adam open here and I've created a new project javascript beginners 4 and i've got chrome here we'll just open the developer tab at the console here and lastly we should go navigate to localhost if you haven't already check out my first video in the series which covers environment setup if you want to follow along exactly the same way I do it feel free to skip this next part because what I'm going to talk about is functions but in a more abstract way because well JavaScript functions for beginners this might be really useful if say you've never done any programming before but if you already have a grasp on the subject then go ahead and skip a bit later in the video so like I said we're talking about functions and the first thing we should go over is what exactly is a function now if you remember back to the video where I described what a variable is a variable is an abstraction a way to give a symbolic name to a piece of information set another way a variable is I could contain therefore some data that you want to store and refer to later so if you're asking like what does that have to do with functions the concepts are more similar than you think so why am I talking about variables when we're talking about functions in this video the concepts are more similar than you think while the variable refers to a sort of tainer for a piece of data a function is like a container but instead of being for data a function is like a container for a piece of code that you want to reuse over and over again maybe in a different way or maybe in a different context let's take an example that shows how variables and functions operate together you want to describe to someone how to calculate the tip at the end of a meal so you tell them normally it's about 15% of the cost of the meal although ever service was really bad maybe give less and if service was superb maybe give more in that case there's a few variables there's the cost of the meal and the quality of the service let's just write those out Boston meal quality service and let's let's give those names that look more like JavaScript variables cost you the to calculate the tip there's some steps to perform and we use those variables to get the answer how much should I tip let's write some what I'll call pseudocode it's not going to be a real code it's just intended to look like code but you should be able to follow along in plain English we'll call this thing the tip calculator and if the quality of service was just okay then tip maybe 15% and the quality of service was great then tip let's say 30% and the quality of the service was just terrible then tip will be will be drunks here and what's up zero so the total tip is the cost of meal times the tip that we decided the function here is the repeatable steps it's the steps involved in deciding how much to tip and then calculating the size of the tip based off of the cost of the meal the function relies on a few variables all of which change with every meal and with every person and those variables are the cost of the meal and the quality of the service or the perceived quality of the service is that was that clear to everyone looping back around javascript functions explained in other ways that they're a way of wrapping up a piece of the code or a section of the code so that it can be used again in different contexts in much the same way that the tipping calculation can now be reused by everyone at the table they just need to input how much the meal cost how good they thought the service was and they get an answer they get an answer of how much they should tip in a lot of ways a function is like a mini program it's a small piece of the program that can be run over and over again in different ways so now that we know what a function is let's move on to how to declare a function in JavaScript and there's a couple ways to define a function in JavaScript if you're really curious and I encourage you to visit the MDM Web Docs that's Mozilla's comprehensive website on development documentation for web standards and they have huge sections dedicated to JavaScript functionality including stuff like browser compatibility which is really nice so you can see whether or not a feature of JavaScript is supported just on Chrome or just on Firefox or across a wide variety of browsers let's go and visit that right now yeah these are the mdn web docs from Mozilla you can see that there's a big section here on functions and it's very comprehensive here but also if we scroll up you can see that we've got a lot of reference for not only functions but all of JavaScript and I use this extensively when I'm learning about JavaScript all right back to how to define a function in JavaScript like I said there's a few ways but I don't want to get too caught up in all that right now since you're new so I'll teach you the most common form to start and we'll work with that at the end of quickly show you a few of the other ways and we won't go into much detail as they require pretty much entire videos on their own the important takeaway here is that you'll know how to declare a function and if you see a different way in code if you're reading someone else's code you should be able to understand what's happening let's go and write some actual code and what we'll do here is we'll write a function that does some console dot log statements like we've been using before so here we go let's just erase all of this stuff here and a function will just write something doesn't matter now to deconstruct what we actually wrote here I started with the function keyword so you can see the function keyword right here and that's one of those reserved keywords in JavaScript and what it does is it says that we're about to declare a function similar to how we used let constant or var to declare variables you use the function keyword to declare a JavaScript function then we follow that up with the name so right here we've got the name of the function and again this is exactly the same as when you declared variables and finally you can see between the two curly braces here I've got the console log statement this is called the function body and you can write a bunch of code here between those two curly braces in fact the same restrictions on naming variables also applied to naming functions now have you missed that video I encourage you to go back and watch it but to summarize you can use either an underscore or alphabetic characters to start that's including capitals or lowercase and then alphanumeric like eight is the zero nine or underscores for the rest of the name let's go and run this now let's go in chrome and hit reload so you'll notice that nothing happened and that's because all we did was declare a function the program knows that the function exists now like write some stuff exists it's a thing in the program but that's all it's doing it's existing there was no code actually run so to make it run and execute and actually do something this is called calling a function in JavaScript and the way you call it is let's just go to the code here and write some stuff then you add a parenthesis afterwards we'll get to why later and then the semicolon and then we just go and reload here and there we go hello how are you you can see that it ran now cuz it printed out the hello how are you that we added in the code before and we can go and we can call this twice for example it was just reload and you can see that it printed out hello how are you twice so this is neat but it's not doing a heck of a lot here so let's add a little bit of complexity let's make the write some stuff function take an argument so we'll go back here we'll add an argument called stuff and we'll just change the internals of the function a little bit so that it writes out stuff now this word here stuff this is an argument to the function which is basically like a variable that only exists inside of the function like the only thing that can refer to it is code that's inside the function that's the code between this curly brace and this curly brace and now and the way you call this function is by doing this so let's just get rendered one of these for now and I right in here I'll pass a string I actually don't like apples I don't know why I wrote that now we go and hit reload and stuff I like apples this is kind of cool stewed viewers might have realized this by now console.log is a function and we've been calling it this whole time and passing in an argument we've been passing it an argument we've been passing it what we want to show up in the console a string now if we go to the console you'll actually be able to see this so I go here and I type type of console log and you can see that it is a function in much the same way that writes some stuff is also a function let's go a bit further now and we'll make that tipping function that we talked about earlier so this is going to be a little bit more complicated let's define a new function here so let's just get rid of all of this stuff and we'll call a calculate tip meal cost the curly braces the curly braces here everything between them is the code of the function we go here and we're going to say let tip size equals new cost times 15% and we're just gonna write out some quick log statements here console.log the Neil cost was Neil cost go let's write out the tip good be size and then the total cost is the total is dududu before we run this I just want to point out that you may have noticed that I used a variable in here let tip size equal the meal cost times 15% what I did here was I declared a variable inside the function and the interesting thing about that is like the argument the argument here meal cost tip size only exists within the function this is called scope and it means as soon as the function ends that variable ceases to exist in the function to give an example of that let's just call the function so calculate tip and the say that the meal was exactly $10 the meal was $10 the tip should be a dollar 50 the total is 11:50 that's about right now if we go in here and we try and use tip size console dot log tip size you might think because the tip size was 1.5 that this is going to log 1.5 but in actuality tip size is not defined as I mentioned tip size only exists for the duration of the function that's when the function starts and when it ends it gets created right here and it only exists for a short time before going away again when the function ends that's when the variable goes what's called out of scope and no longer exists let's get rid of this and we'll add a second argument to the tip function now let's call it drink cost so the reason I added a second variable is you can notice that I just used a comma to declare it I didn't have to do anything fancy all I have to do is add a comma and then the name of the next argument and the way we call this as we go to calculate tip and we just added a comma here and let's say that the drink was $5 you got a fancy juice or one of those sparkling waters and then we run it out we actually have to modify a calculate tip to take that into account there we go and there we go the meal cost was fifteen dollars that's ten plus five the tip should be 225 the total is 1725 that's exactly what you should expect now the last thing I want to cover here is that a function can do some work but you can also get JavaScript to return a value from a function maybe you don't want to just calculate the tip and then print it out but maybe you want to get the number so that you can add it up for everyone at the table let's modify the function yet again so first off I'm just going to simplify this a little bit just gonna get into this I can get rid of these and what we're gonna do here is we're gonna return the value so now so the return keyword is a reserved keyword in JavaScript much the same way that function and var and Latin cuz those are all reserved keywords this is a reserved keyword it tells JavaScript that you want to save the value in this case tip size and you want to pass it back to the spot that called the function now when I call this nothing happens but I can use the value and then it'll show up so let's go and do that let's just print it out so I do a console log and hit reload we should print it out there we go 225 and you can save it so instead of using consult log let's save it to a variable go here would remove this now we'll call this again so let's go here that tip to equal calculate and let's say the second meal is 20 dollars and they didn't have anything to drink and we'll do some console dot log here log tip 1 now let's go to Chrome and reload and there we go you can see tip 1 was saved 225 tip 2 was saved $3 so the total tips was 525 those were written out here so we have a console dot log that writes out tip 1 and tip 2 and then we have a final console dot log that writes out the combined tip 1 plus tip 2 now earlier I said there were multiple ways to define a function and there are the one that we've been using up until now is called function declaration so that's use the keyword function followed by the name and then all the arguments and the body of the function but there's a few other ways I'm going to go through a few of the others just for completeness sake now so you'll know they exist you'll know roughly what they do and if you want I encourage you to modify the examples in this tutorial and try to use the other ways of declaring a function instead of the function declaration way so another really common way is to use what's called a function expression I'll get rid of all this code to start to do and it looks like this this is called exactly the same way nothing really changes just going right some right and more stuff then go and reload and writing more stuff so going over this a little bit we have the function keyword here and there's no name after it this creates what's called an anonymous function expression it doesn't have a name but since we assigned it to a variable that's that's the thing you can do you can still refer to it by using write more stuff and you can see that this is still a function which is use console.log type of write and more stuff and there you go it's still a function in this example we've created what was called an anonymous function expression you can also create a named function expression so so I'll just go here and I'll copy this now let's hit reload you can see that it wrote more stuff again this time from named so we got writing more stuff function writing more stuff function the the type of write more stuff and write more stuff again we're both functions still this is called a named function expression and one of the major differences between it and the anonymous function expression is that it has a name as you can probably tell the reason that you give it a name is because if you have an error in your code and it's an ax named function versus an anonymous function you may just have a little bit more information about what happened so sometimes it's useful just to give it a name but you don't have to now if you're wondering here what the difference is between the function expressions and the function declarations that were using throughout the tutorial the really big one is this so I'm just gonna get rid of a lot of this stuff we're gonna keep the anonymous one for now and let's go here and I'm gonna use a and I'm going to declare a function the way that we were declaring it earlier function this is this now from the name you might be able to tell what's gonna happen but I'm gonna run it here so I'm going to call the function this ran successfully now the really interesting part is I can put it before the functions declaration and it still works and the reason for that is because this function this exists no matter what exists as soon as the file is loaded and parsed now if you try to do that with the function expression you go to write more stuff here and you try and use it before it was created this is gonna error out because in the second case in the function expression case the function only exists after this line of code is hit that's the biggest difference between these two and yes there's other reasons why you might want to use one or the other but let's just ignore that for now it's we're getting into an advanced topic and we'll get to that down the road lastly there are what's called arrow functions just get rid of the code here and let arrow function equals here we go and reload oops did run it when we reload we see I'm an arrow function this is really similar to the function expressions in fact you actually have to go and assign it to a variable just like a function expression if you want to save it for the sake of simplicity you can consider them basically to be the same thing that is arrow functions and function expressions there are differences between the two but we'll have to do much deeper dive on the differences later so here's a challenge were you able to change the code to use function expressions or arrow functions let me know if you did in which one you tried and that about wraps up this video in the series I really hope you enjoyed it and I'll see you again soon Cheers
Info
Channel: SimonDev
Views: 1,065
Rating: 5 out of 5
Keywords: Javascript functions, javascript functions explained, how to declare a function in javascript, javascript functions for beginners, javascript function arguments, javascript function declaration, anonymous functions javascript, named functions javascript, how to create javascript functions, javascript for beginners, named and anonymous function in javascript, function expression vs declaration javascript, javascript tutorial, anonymous function, function expression
Id: xrhAKA0niFQ
Channel Id: undefined
Length: 25min 4sec (1504 seconds)
Published: Fri Dec 13 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.