From the course: Computer Science Principles Lab: JavaScript

Use functions to repeat actions - JavaScript Tutorial

From the course: Computer Science Principles Lab: JavaScript

Start my 1-month free trial

Use functions to repeat actions

- [Instructor] Functions are named sections of code that we can execute using a single statement. In Java Script we use the function statement to create a function and surround the code of the function using a pair of curly braces. Let's write some java script code and then learn how we can use functions to call them. First let's create a new variable and store a value inside of it. Inside our script.js file I'm going to create a comment, create a variable, then we'll use the var statement to create a new variable and we'll call it myScore and we'll set it equal to an initial value of 1,000. Then we can manipulate the variable by adding 100 additional points to the existing value and assigning that back to itself. We can do that by taking myScore, using the assignment operator, assessing the current value of my score and then adding 100 to it. Finally we can use the console log method and send the score to the browser. We start by accessing console, then a period then the log function, and then a semicolon. Inside the parentheses we're going to put in a simple phrase, Player score: period, wrapped in a pair of quotation marks. Then we'll add or cancatinate the myScore variable. In this case we're taking a string and are cancatinating or adding an additional string to it at the end. Since myScore is a number it converts it to a string in order to cancatinate it to the first phrase. If we save this file and open the index.html document in Chrome you'll see the following output. The code ran without any problems and we can see that the value 1,100 is currently in the myScore variable. But if we wanted to add more to the score we would have to write this code over and over again. If we wrap it up as a function we can call the function as a shortcut. To do this we need to create a new function. Below the code let's create a new function and we can move some of the code we already wrote into the new function. We start with the function statement followed by the name we want to give the function and then add a set of parentheses. We'll call this changeScore. Then after this create an open curly brace and a closing curly brace is created for us. Separate them with an empty line. I should point out that the position of the curly braces is entirely up to you. Some people put the opening curly brace after the function statement on a separate line. Some put it after the statement on the same line and some functions are so short that they just put everything on a single line. The location isn't important and you will find that programming languages have best practices or agreed upon rules in how your code should look. So you will see different versions but they all do the same thing. We now have a function called changeScore. It doesn't do anything but we can move our code from earlier into this function. Move the second two lines of code we created at the beginning into the function. I'm going to remove the space in between them and then I'm going to indent them over so they're easier to read. You might ask yourself why move only the last two lines? Well it is related to variable scope that we will define more clearly later on. It defines where variables live in the code. We want the score to live in the main part of the program so we define it there, outside of the function. We will go more into depth about what that means soon. Now let's run the code and see what we did. If you reload the page in Chrome you might scratch your head and wonder what happened because nothing appeared to happen. The console is now empty. Aha, but we changed the code and a function only runs when it's called. When we move the code into the function we now no longer are just running it line by line. We encapsulated it within the function and in order for that code to run we need to call or invoke the function by using the function name. Go back to the code and after the line with the var statement call the function using the function name, changeScore, with a pair of parentheses and a semicolon. Now save and reload the browser. You'll see the output is the same as it was before and now it's running the code from the function. To confirm this click the statement at the end of the console line that reads scriptjs:10. This will open the file and it will highlight the code where the output to the console took place, in this case on line 10, which is inside the changeScore function. We can also create a function that will initialize our little game here. Many times developers will do that to help set things up at the beginning of the game. We can refactor our code to support this by creating a new init function in our code. We can place it above our changeScore function. We'll start with the phrase function and then we'll create a function name init. You have a pair of parentheses and then our pair of curly braces. In this init function we can set the initial score of myScore. When you create a variable you don't have to immediately give it a value, you can just create the variable and define its name and not provide it a value quite yet. We can refactor our code to do that here. We'll remove the assignment operator and 1,000 from line 4 and then we'll add that inside our init function. Now save and reload the browser. Huh, what, nan? Well nan stands for not a number. When you try to manipulate a value as a number but it isn't a number you get this as the value. Here's why it happens in this case. We first create the variable myScore but we don't give it a value. It has a value of nothing sometimes referred to as null. This shouldn't be confused with a value of zero. Zero is a value. It represents that you have zero number of something. A value of null means that the variable is devoid of any value at all, it is empty or null. The line where we assign the value 1,000 to variable never runs because we never run the init function in our code. So when we try to add 100 to the value in the changeScore function it doesn't know what to do because it asks add 100 to what? And since there is no value it evaluates as nan. To fix this we need to run the init function. So we can do that before we call the changeScore method in our code. In between the var statement and the changeScore function call we'll add in a call for init. Now if we save and reload in the browser you'll see that things are working properly again. As a programmer it's also a good idea to create comments in your code to help make your code clearer. I won't do this all the time to keep the lesson shorter. But if you refer to the code files that are part of the course you'll see that they are comments inside. For this video we can walk through how to make good comments in your code. First I should define what I'm doing at the beginning to be more clear. I'll change this comment to create the game score. Then I'll create a new comment here, setup and change the game score. Then I can explain what happens in each function in the game. Function to initialize the game score in the game. Function to change the score of the game. At the end I have code that looks like this and now if you come back to this later or if someone else looks at your code it'll be much clearer on what the program does. So to create a function you will use the function statement followed by the function name. Then after a pair of parentheses you will list all the lines of code that are in the function and wrap them with a pair of curly braces.

Contents