JavaScript the Basics for Beginners - Section 4: Functions | Rob Merrill | Skillshare

JavaScript the Basics for Beginners - Section 4: Functions

Rob Merrill, JavaScript Instructor

Play Speed
  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x
7 Lessons (33m)
    • 1. JavaScript the Basics - Arrays: Promo Video

      1:55
    • 2. JavaScript the Basics - Functions: Intro

      4:30
    • 3. JavaScript the Basics - Functions: Intro Lab

      3:46
    • 4. JavaScript the Basics - Functions: Deep Dive

      5:31
    • 5. JavaScript the Basics - Functions: Deep Dive Lab

      5:03
    • 6. JavaScript the Basics - Functions: Scope

      5:23
    • 7. JavaScript the Basics - Functions: Scope Lab

      7:02

About This Class

Course 4 - JavaScript Functions

In this course you will cover: 

  • Function Expressions
  • Function Declarations
  • IIFE's
  • Function Scope

Through our whole JavaScript the Basics for Beginners course series you will find this is your one stop necessary to enter into the language of JavaScript. We are going to start from scratch and build up our understanding of the world's most popular programming language together. 

View JavaScript in action with whiteboard videos optimized for viewing on your smartphone. This is truly a course that you can engage with no matter where you are. Take your JavaScript eduction on the go! With whiteboard videos you get to visualize what JavaScript does under the hood. 

You can practice JavaScript in your web browser! Take advantage of Google Chrome developer tools to put the JavaScript you have learned during our whiteboard lesson into practice with further examples and challenges. This is our JavaScript playground.

Learning JavaScript is like learning a language. This course won't make a false promise of saying you will master JavaScript overnight. However, this course will immerse you into the world's most popular programming language. 

Each course will introduce you to something new in JavaScript :

  • JavaScript Syntax
  • JavaScript Building Blocks
  • JavaScript Best Practices
  • JavaScript Objects
  • JavaScript Arrays
  • JavaScript Regular Expressions
  • JavaScript Functional Programming
  • JavaScript Algorithms
  • JavaScript Data Structures
  • JavaScript ES6 Syntax

You'll finish this course with an understanding of JavaScript that will let you take a deeper dive into the language and possibly launch you into a new career as a JavaScript web developer.

Learning a new language can be difficult and even feel intimidating. JavaScript the Basics makes the the learning process feel accessible and welcoming!

Transcripts

1. JavaScript the Basics - Arrays: Promo Video : Welcome to Java script. The Basics. JavaScript is the most popular programming language in the world has been called the language of the Web Stack Overflow listed as the most popular deaf technology and get have numbers it as the top ranks language learning JavaScript will allow you to be a full stack developer or fund a specialty on the front end or the back end. With JavaScript, you'll be able to cope with front and frameworks like react and angular on the client side . And you can also cut on the back end server side with no Js and create databases with Mongo . DB JavaScript is a language, so it's going to take some time to learn before you can write poetry or a novel in any language, you have to first learn the languages alphabet, how to make words and see how others use it. To learn JavaScript. We're gonna look under the hood. This isn't just going to be an exercise in copying someone else's code to wind up with an application you don't understand. Everything we do will be visual in the form of a whiteboard lesson where you can really see how everything works and connects. If you are a visual learner, this is the course for you. This isn't about going 0 to 60 or zero to hero, because if you really are starting at zero, those courses leave you behind quickly. It's about learning. Understanding and applying is that you could build and create with JAVASCRIPT. Way will then follow our white board. Lessons into the lab way will enter into the Google Chrome software developer. Consul thistles are Java script playground. There is nothing you will need to download for this course. No special tools, no extra steps. Just Google, chrome, everything. You learnt the lesson we will then recreate in the lab together. I'll then give you a code challenge to recreate what we learned together and then we'll look together at a possible solution. Welcome to Java Script. The basics. Let's start speaking job script 2. JavaScript the Basics - Functions: Intro: Welcome back to Java. Script The basics. In this section of lessons, we're gonna look at functions. What is a function Functions let you group a serious of statements together to perform a specific task. If different parts of a Scripture Pete the same task, you can reuse the function rather than repeating the same set of statements. Functions like a razor objects, but you can think of them as the verbs of the object world. They're like the button you press to get the result you want. They let you group a series of statements together to form a specific task in Java script. If you find yourself writing up the same thing over and over again, this is a sign that you can create a function to do that for you. There's a term called Dry in the programming world it stands for. Don't repeat yourself, and that's what good programmers dio. They don't repeat themselves and this lecture. We're going to look at the anatomy or syntax of a function and declaring that function. Let's start with looking at some code. We'll start with a function declaration later. Lectures will allow us to look at different ways of using and writing functions. Here we have a drama stripped keyword like var. It is a key word, reserved word function, letting our JavaScript interpreter know that we're creating a function. Next, we have a function name or identifier. This won't be true of all functions, and we'll see examples of those in upcoming lessons. The name will need to meet all the qualifications and best practices of naming variables we saw in our variable lesson. This means that it can start with an upper or lower case letter, dollar sign or underscore. They can't start with a number, use a keyword or contain spaces. Function names are often verbs or phrases that begin with verbs after the function. Keyword invariable name are open and closed parentheses, in which you have the option to place parameters. They will be executed when the function is called or in vote. We will live this blank for now, but we'll see some examples in a moment. Next, we have the code block. The two curly braces are the indicator of the code block or function body. The steps that the function needs to perform in order to performance tasks are packaged up in a code book. A code block consists of one or more statements contained within curly braces, and you do not read a semicolon after the closing curly brace like you do after a statement . Now we're in a position to call our function. Now that you've declared the function, you can then execute all of the statements between it's curly braces with just one line of code. This is known as Cohen the function or invoking the function. The body or code block of the function between the two curly braces is not executed when the function is defined. But when it is in vote in programming language, you would say that this code calls a function. Sometimes you'll find yourselves declaring a function that needs information. This will involve dealing with parameters and arguments. Arguments and parameter names are just placeholders. Their names don't matter is the order that will be important. However, having said that, being human readable is important and their names do matter for those will be working on your code with you or after you. Let's look at another function and the declared function You have what are called parameters. Parameters will be filled by what has entered. When you call a function calling a function, our function in vocation will be the time to provide values or arguments for the functions parameters. Here, Abraham is the argument for the first name parameter, and Lincoln is the argument for the last name parameter. So remember, parameter is the term we use for the code in the function declaration. An argument is the term we use for the code when we call the function. No, we can run this function several times. You could do this for multiple presidents. We could put in George Washington to to get the name of our first president. We could put in Thomas Jefferson degree Thomas Jefferson and so on. That's all. For now. We have just taken our first look at functions. We'll see you next in the lab where we put what we have learned into practice. 3. JavaScript the Basics - Functions: Intro Lab: all right in this lab. We're going to review our lesson on function, syntax and using arguments and parameters within a function we saw on our lecture. The functions air going toe have a keyword function. They may be named or anonymous, depending on the result that you want and contain a code block. This particular block of code won't run until the function has been called or in vote. Let's go ahead and begin with building a function together. Let's create a variable that greets our neighbor. Good morning. So we have function Good morning, neighbour and we have a code block saying Return Good morning, Neighbour. Let's go ahead and run a line of code that invokes a call and runs the function. That's simple enough. Let's let this sink in by creating another function quickly. This will be telling our neighbor good evening and you're thinking them for something that they have done so we can clear out what we have. We have function. Good evening, neighbor, and we have a code block that returns a string saying Good evening, neighbor. Thanks for everything. And then we invoke the function. Good evening, neighbor, and we return good evening, neighbor. Thanks for everything. Now, both of these functions are a little impersonal. Sounds like you don't know your neighbor very well. Here is the challenge. Rewrite both functions to include parameters and arguments with real names. And in the second function, where it says Thanks for everything that's pretty generic. Make sure you have a parameter, an argument that allows you to be more specific about your neighbor when you call your function. So here's your challenge. Rewrite both functions, including a parameter an argument for name in both and again in the second function, replace everything with a parameter, an argument naming a task. All right, good luck. Go ahead and pause the video and we'll come back and front of solution together. Okay, help that went well for you. If that was a little difficult and complex. That's all right. There are a few moving parts in this scenario. Let's start with a good morning function. Go ahead and give it the parameter name. It could really be any parameter, but for the readability, we want a parameter that makes human sense. So we choose name. We will then return a string of good morning with a space holder and Wilken Cat that using our assignment operator with the name parameter. Next, we'll go ahead and call or invoke our function. Good morning, and we use the argument of Joe. The result is Good Morning, Joe. Our last challenge is to take the good evening function and pass it to parameters and invoked that function with two arguments. Let's go ahead and look at it really quickly. We have the function, good evening and the code block return. Good evening, neighbor. Thanks for everything. We want our arguments and parameters to specify neighbor and what you were thinking them for. For the first parameter, we're gonna put name as in our previous example, our second argument could be anything but We'll put the word task and the code block will write some code that takes in two parameters and can cats them together with the strength we have to be Astra Special one. Outing these strings together to have the proper spacing included. Let's go ahead and invoke our function by giving it the arguments. Good evening and then for name will put Hank and for the task will put taking the trash to the curb and the result is Good evening, Hank. Thanks for taking the trash to the curb. That's all we have for this lab section will see in the next lecture. 4. JavaScript the Basics - Functions: Deep Dive : All right, welcome back to Java. Script. The basics. In this lesson, we're going to take a deeper dive into functions. Last lesson. We looked at function, syntax and a function call. In this lesson, we're gonna look at function expressions, anonymous functions, and if he's I know strange work. At first, these differences air going to appear to be subtle, and the application not is clear. But as you move deeper into programming, it will be necessary to use them appropriately and understand the differences in what the JavaScript interpreter does with them. So for now, our task is to learn to identify each of these and learn how the JavaScript interpreter interacts with each one. Let's start off with the function expression. This is when you assign a function as a value to a variable, a sign of function. Toe variable is when we put a function in a container or box, and we label that box with the variables name. So to get that data we call the variable to get access to it. Let's look at our function from last lesson and draw a comparison. We have the function keyword, then the function name, and then we enter into the code block, which is a return statement given us this string. Good Morning, neighbour. This is a function declaration function. Declarations Air, always named now, was looking a function expression in comparison. As we look at the two and look for the differences, we can see that a function expression isn't named. It can be, but because the function is stored in a variable, it isn't necessary to name the function. To access it in this case would be unnecessary code. This makes it what we call in anonymous function inside the variable. Now, if we just enter, are variable into the console, we won't get the results of the function. Remember, a function doesn't run until it is called or invoked. Instead, we simply get the whole function return to us. We need to invoke or call our variable, which then runs our function and returns its value. Here's the noticeable difference. This may take a while to sink in. The JavaScript interpreter always looks for variable and function keywords before going through and running each line of the script. It's okay if that's a little confusing. It's a bit complex, and you don't need to have a full grasp. At this point, Just be aware that the JavaScript interpreter looks for variables and function declarations before running its code. The big difference is that with the function declaration, you can call the function before you even declare it in your code. This is because the JavaScript interpreter finds this word function and its value and stores it before it starts to run each line of the code. So when that function is called, the JavaScript interpreter already knows about it. However, for the function expression, we don't find this. The JavaScript interpreter looks at the word var and hoisted up to the top. Hoist is determined concept. We will take a deeper look at in another video, so don't worry about that too much right now, but it list this variable to the top and stores its value as undefined to the variable. So if we try to invoke or call the function expression at this point, we're going to air out. The function has not been defined. The interpreter doesn't know about it yet. It's a subtle difference to a new programmers eyes and is going to take some time to sink in and to see the difference is it can make. We will get some time together in the lab to practice this a few more times. Let's close out this lecture by looking at another thing we could do with functions. This is called the F E. It stands for immediately invoked function expression. Let's look at a code sample. This looks just like our function expression, where we have the function stored within a variable. If he's are also okay to make anonymous functions as well. Right now we will store it in a function expression. What's new is this extra set of parentheses at the end of our function expression. This is what is going to call the function is where you put any arguments you might have. Then all of that is wrapped within another set of parentheses. Also, we can put the closing parentheses after the rap function, although best practice seems to have the closing set of parentheses wrapped up within the whole function. In our previous examples, we saw that the function had to be called for the code in the function to run. In both instances, if he's aren't waiting around to be called Instead, they're executed once the interpreter comes across them. As the JavaScript interpreter comes across these two blocks of code, it interacts with them differently for the function expression without an iffy. The value stored inside the variable is the function whose code block has not yet rant when it runs across a function expression with an iffy stored in the variable, it stores the results of the function. It stores the code that has ran again. The importance of this may be hard to spot now, but one benefit of immediately invoked function expressions is to ensure that variable names do not conflict with each other. That's a big deal in programming, and we'll have more on that later. Thanks for joining me in taking a first look at function expressions, anonymous functions. And if he's and I'll see you in the lab for some hands on experience 5. JavaScript the Basics - Functions: Deep Dive Lab: All right. Welcome to a lab time and our lecture. We looked at function expressions, anonymous functions. And if he's we started investigating Hava Java script Interpreter interacts with the way that we write our functions. We saw that a fortune expressionist signs the function as a value to the variable ah, function Expression like a function declaration must be called are invoked within our code to be ran. We were also introduced to anonymous functions which go without a function name. Then we looked at If he's that these air blocks of code that are run immediately and don't need a separate invocation or call to run them, it was pretty complex stuff. And if you're new to programming, it probably got real complex real quick. Let's break our lesson down into pieces in the lab and break down some of this complexity. Let's start off by making a function declaration. Remember, function declarations must be named later. I'm gonna ask you to turn this named function into a function expression. Let's create a function declared knock knock within its code block. We're going to return the value of a string sane. Who's there? A function declaration is not an execute herbal statement. So it isn't common practice to end function declarations with a semicolon. Your first challenge is going to be a review. I want you to simply call this function. Go ahead and pause this video and give it a shot. All right. Hopefully that was pretty easy for you. We're going to simply put knock, knock, fold by the parentheses to call the function your next challenge after you pause. This video is to turn this name function into an anonymous function and store that anonymous function within a function expression. I then want you to call the function. All right. How that go hopefully was pretty straightforward. Let's solve this together. We're going to give a variable name again. This could be any variable name. It could have been knocked times two. Next. The value we give the variable is an anonymous function. We simply remove the name. You don't have to do that, though. However, since it is being a sign of the variable keeping the function named isn't of much use to us right now. So now let's look at the value of knock knock and we simply get the function that hasn't run yet? No. If you want to call this function, we just invoke our knock. Knock variable and we get Who's there. Great. Now let's build a nifty remember And if he is immediately invoked, function expression. These air function is that Iran immediately, and you don't need to invoke or call them with a separate piece of code. They're anonymous functions that are immediately invoked. Let's start with the declared function we'll call a dog. Walker will give the parameters of person and dog, and the co block will return the argument for person. And the string is taking than the argument for dog, followed by the string for a walk. Then we will go ahead and color function and give it arguments for person and dog. The result is Paul is taking Charlie for a walk. Now here's our challenge. I want you to turn this into an immediately invoked function expression than your second challenge is. To put that if he inside of variable of your choice and call the variable. All right, go ahead and pause the video and give it a shot. Then we'll come back together to find a solution. How'd it go this had a few moving pieces, so don't be discouraged if you didn't get it. We're going to wrap this whole function parentheses inside. We have removed the function name to make it anonymous. We then Leicester parameters of person and dog. We run the exact same code block than immediately after that. We invoke our function with the arguments of Paul for person and Charlie for dog. And we get the same results. No, we're going to store this function within a variable to save some time. I'm just going to press the up era of and set variable dog walker equal to that. If he remember in previous lessons that in a function expression that if we return the variable, we only get the function with its code block return to us and not the results of the function that has ran. Not so if if he's we simply have to input the variable and the functions value, not the function is returned. Pretty cool, right? Hope that this is starting to make a connection with you. Thes two lessons dove a bit into the deeper end of javascript. If you found yourself struggling, it would probably be a good idea to go back over these two videos another time or two to keep pace with future lessons on functions. That's all for now. Thanks for taking this deep. Dive into functions and we'll see you in the next lesson. 6. JavaScript the Basics - Functions: Scope : All right, welcome back to Java. Script. The basics. This is going to be an exciting lesson as we look at function scope. What is scope in JavaScript scope is where variable is defined. Java script has two scoops global and local variable that has declared outside of function definition as a global variable, and its value is accessible and changeable throughout your code. A variable that has declared inside a function definition is local and not exposed to the rest of your code. The rest of this lesson and our next lab are simply going to be unpacking this definition. Let's look at some code here. We have declared a variable named scope and assigned it the value of the string public. It is a global variable, meaning that we can access it anywhere in our code. Next, we have a function declaration with the name checks go and its code. We haven't declared a local variable called scope. It has the same name and we have assigned it a value of the string private. This means that it is only accessible within this function. We close out the code block by returning our value of the local variable scope. All right, let's access both of these scopes. When we look for the value of scope we can't see inside our function to the only scope we see is the scope with the value of public, which is a global variable. If there were no global variables of scope, are Java script interpreter would return an air to us because it local scope is hidden. It would see no instances of the variable scope. If we want to grab the local scope with the value of private, we actually have to call the check scope function so we can have access to its local variable. Now let's look at another section of code that is almost identical. The only difference is the addition of a declaration of a new variable called New Scope, with the assigned value of the string global variable. Then, inside of our Chek scope function, were returning an array of the variable scope and the new scope. So if we look for new scope globally, we will find it. Since we have access to all global variables, look what happens when we run the check scope function. We get to return values of the local variable for scope but also the global variable for new scope. Children have access to everything their parents have if they don't first have the resource . This is called scope chain. This is like a child not having money but having access to their parents. Money. This is like a child not having transportation but having access to their parents. Transportation. Let's talk about the scope chain Samore. When Java script needs to look up a value of a variable, it starts by looking at the first object in the chain, the local scope and if it finds it, it uses that value. If a dozen it searches the next scope, it is contained within. In this case, it's the global scope. If the value is not found within the global scope, it will return in air. In our example, Scope was able to find a value locally, so it used it but had to move up the scope chain to the global scope to find a value for new scope. Let's look at this another way. The global scope cannot look inward, but the inward scope can look outward. Let's go ahead and close out our lesson by looking at. One more example is something that we skipped over in our variable lesson. It is the importance of declaring our var keyword when we make our variables. Let's look at some code if we don't declare the var keyword are variable is automatically a global variable. Technically, throat this course. You have declared your variables without using the VAR keyword. But it is always best practice because of how scope works and JavaScript. Let's look at the trouble we can get into if we don't use the var keyword. Let's go to our original lines of code, but we'll make one. Change will take the var keyword off of the scope in the Czech scope function. Now, when we look for the value scope, we will get public as expected. Next, if you run the check scope function, we will get our expect drizzle of private the same as before. Now, if we run the scope value again, it should be looking globally, and when it does, it returns private because we didn't use the keyword var. That check scope function does something we don't expect. The value is a global value, and we have naming collisions that will give us unexpected or undesired results. One way that you keep this from happening is by using the EU's strict mode. Unfortunately, you can't use this in your consul like you can in a text editor, but it will be important for you to know and the lab. I'll show you a trick to simulate this, using an iffy that we looked at in an earlier lesson. Why the strict mode Strict mode makes it easier to write secure JavaScript but changing previously accepted bad syntax into really errors. That's all we have for this lesson. Thanks for taking a first look at function scope with me, and I'll see you in the lab. 7. JavaScript the Basics - Functions: Scope Lab: All right, welcome back to the lab. In our lesson, we looked at function scope and JavaScript. Scope is determined by where the variable is defined. There are two kinds of scope, global and local. In our lesson, we saw that local scope is hidden from our globalize. We also saw that global scope is not hidden from our local eyes. In other words, the global scope cannot take. Resource is from the local scope, but the local scope is free to use the values and resource is found in the global scope. This is what we call the scope chain. We also took a quick look at the use of strict mode to keep us from polluting the global name. Space scope is a big deal on JavaScript at an extremely important fundamental as you develop with more complexity. So let's get started. Let's go ahead and build a function together, will declare a function and call it road trip. Within its code block Willis two variables gallons and set it equal to 12 an M P G mpg, which will steady equal to 34. We will then return the value of gallons times MPG, then we invoke our function and get the result of 408 Pretty straightforward. Here is your challenge in our lesson. We talked about how the scope chain works. If a child scope does not have a value within its scope, it can look up a level to find that value. It can keep doing this all the way up the scope chain until it reaches the global scope. If at that point it still doesn't fund the value it is looking for, it will return an error. I want you to take those local variables and move them to the global scope. Then we'll come back and find a solution together. Go ahead and pause the video. All right, How to go? Hopefully that was no problem. I'm going to quickly come up with a bad practice solution and follow it with the best practice solution. Here is the wrong way. We can simply bring up our code again using the up arrow. If we run gallons, we will receive a value of Ember 12 and NPG will give us the value of the number 34. From there we will remove the var keyword from our variables gallons and PG. Remember, if we do not use the var, keyword are variable will automatically be global. So when you first declare variable, it is always the best practice to use the var keyword. So we don't get our global name space filled up with naming conflicts. So let's solve this the best way. Now it is a simple is declaring gallons and miles per gallons outside of the variable. And if we look, we can see that we have access to them as global variables. And we can still run our function and go up the scope chain to grab those values. OK, I mentioned how it is bad practice, not user of our keyword. So let's avoid the negative side effects that can come with bad practice. The solution to this is the use, the use strict mode. This doesn't quite work in our crew developer tools, as I mentioned in our lesson as it would in a text editor, but we can simulate this by creating an iffy and then using the strict method. So let's go ahead and wrap a function. And within that, let's put use strict. So now we have this iffy and we can put a variable without declaring a keyword will say food equals pizza. When we run this code, we get an error. That food has not been defined to be clear, wrapping the use strict mode and if he isn't terribly relevant for coding in the real world , you don't have to go to that measure to implement strict mode in your text editor. But it is an important illustration in Google Chrome for how you can keep from making simple mistakes that could create some bugs in your code in the real world. Okay, so here is our big challenge for the lab nested functions. We didn't do this in the lesson, but it's the same concept as a local scope. Being within the global scope. I want you to create a function within a function, so that means you will have a global scope within that you will have a function you have created and that will create a local scope. Within that function, you will have another function, which is a nested function. I want that function to go up one the scope chain to grab of value from its parents, cope and then go up one more time of scope chain to the global scope and grab a value. I then want you to run the code in such a way that it calls on the innermost function that might rack your brain a bit, and it's OK if it does. If you can't come up with a solution quickly, that's OK. I would suggest setting a timer for at least 20 minutes and struggle through it. After that, time will come together and look at one possible solution. I want to repeat that your growth as a Java script developer is not going to come through copying someone else's code. There's some benefit to that, but real growth is in the struggle. Go ahead and pause the video and in a few moments will come up with a solution together. All right, let's go ahead and create a nested function that is going to find the volume of something two sulphur volume. We need to have length times with times heights. Now the solution for this is not the most efficient solution for funding volume in real life or even encoding. It's just a practice working with scope chain with a point of reference that we have in common finding the area of an object. Our goal is to have the child scope grab from both the parent and global scope. So let's declare a global scope Variable will call it height and a sign it a value of 10. Next, we're going to create what will be the parents cope. This will be the scope that we call. When we invoked the function, we'll call it volume. Within this, we will place to local variables invisible to the global scope but visible to the future. Child scope will declare a with variable and assign it the number 10 and the late variable ascending at the value 10. Next will create a function expression and will assign it the value of a function which will be our child scope. The code block will look for the length, width and height within its local scope, and it won't find it. So it will go up the scope chain and find with and lengthen the parents cope and then go up one more level of the scope chain to the global scope to find the value of height. Now, as we finish that code block, we want to return the value of volume of object variable. Now, as we finished that co block, we want to return the value of the variable volume of object. This way, as we call our function volume, we get our value. As I said in general and real life and coating, you will never find volume like this. However, this displayed scope, scope chain and nested scopes at work. Thanks for taking a first look with me at function scope and we'll see you in our next lesson.