What do you want to learn?
Leverged
jhuang@tampa.cgsinc.com
Skip to main content
Pluralsight uses cookies.Learn more about your privacy
Quick Start to JavaScript: Volume 2
by Susan Simkins
In this second Volume of the Quick Start to JavaScript tutorial, we'll learn more methods of control flow like switch statements, for loops, and while loops. Software required: Mozilla Firefox, Brackets, Google Chrome.
Start CourseBookmarkAdd to Channel
Table of contents
Description
Transcript
Exercise files
Discussion
Learning Check
Recommended
Introduction and Project Overview
Introduction and Project Overview
Hi, I'm Susan with Digial-Tutors and this is Quick Start to JavaScript Volume 2. In this course, we'll learn more methods in Control Flow like using Switch Statements, For, and While loops. We'll learn how to create reusable commands using functions, how to store values in arrays, and how to loop over an array. We'll also learn how to create JavaScript files from scratch and how to create a plan and break down code into steps so we can make it easier to write code of our own. We'll finish up by creating a more complex version of our Zombie Text adventure game from Volume 1. So let's get started in our next lesson by learning about control flow using switch statements.
Quick Start to JavaScript: Volume 2
Switch Statements
In this lesson we'll learn about control flow using Switch Statements. To get started, just like we did in Vloume 1, we'll be opening our project files in Firefox web browser and using the Developer tools to write our JavaScript. So we want to go ahead and open up our 02_begin folder from our project files, and just double-click our index.html file to bring this up in Firefox web browser. So I'm going to go ahead and exit out of this since I have two duplicate windows. And to pull-up our Scratchpad here so we can write our JavaScript, we just want to push F12 to pull-up our Developer tools or we can also right-click and come down to Inspect Element. From here we just want to click on this little spiral notebook icon, and this will pull up our JavaScript ScratchPad for us. So I'm going to go ahead and shrink our window here. I have our Console tab pulled up just in case we want to use our Console for debugging or anything like that. And I'm also going to go ahead and delete this, comment it out the comment here in our Scratchpad that it adds by default, just so we have a nice blank file. If you remember in Volume 1 one of the last things we learned about, syntax wise, was using an if else statement to create something called control flow, or writing code in a non-linear fashion. So I want to take a look at how we can use something similar to an if else statement to check for multiple conditions and run code only if that condition has been met. So we can also use something called a switch statement. And the syntax for this looks a little bit different, which if we hover our little button here, we can take a look and kind of preview what this is going to look like. And what it's going to use is this switch keyword, and then we're going to enter an expression or an argument in our parenthesis. So for example, this is just using n, which is just a meaningless placeholder here for whatever we want to put in here. And then we have a list of cases that are going to be defined with this case keyword. And so we can see our first case here. We're going to specify what that's going to be. So example1 is kind of this example, and if it finds that this is = to our original condition then it's going to go ahead and run the code right underneath there. This is a little bit harder to read at first because if --- in an if else statement we have brackets or blocks of code, and in here we use just indentation to kind of separate that or organize that. So we have our case and then we'll set what we want our case to be and then we'll run this code if that is = to our original condition here. And then this break keyword is going to tell it to break out of our switch statement because that condition has been met. So we have four major parts here. We need to use the switch keyword, our case keyword, that break in each case or condition, and then the last thing we need is this default condition, which is going to run if none of these other cases is true. So just take a look at this let's go ahead and create our own switch statement and kind of do something maybe a little bit fun here and create a switch statement that's going to read out our horoscope. So to do that the first thing we want to do is we're going to ask the user what their sign is. So if you remember, we can use a prompt to ask a question and we need to remember that response by storing it in a variable. So I'm going to create a variable using that var keyword and then we'll just say var sign, and then we'll set it to = a prompt, which is going to ask our user whatever question we put inside here. So I'm going to say, "What is your astrological sign?" And then add that semicolon and now we can use our switch statement to run code based on what that response is. So we're going to come in down here and start our switch statement. So if you forget that syntax you can come over here and hover over this and get a little hint at our syntax here. So we want to use that switch keyword, if I can type that in correctly, and then in our parenthesis we're going to enter what we want to switch out for our different cases we're about to list. So we want to switch that sign we just created. Then we need to open and close our curly brackets and we can start with our first case. So let's say our first case the answer might be something like, "Taurus". Then we need to add our colon at the end of our case and then press Enter to come onto a new line, and we need to add what code we want to run under this condition. So let's say we want to alert a horoscope or a little fortune or something like that. We'll put it inside of this. And then we'll need to break out of that statement using that break keyword. So I went ahead and wrote out kind of a little horoscope here. So I'm just going to Copy and Paste that in. You can feel free to type that in or you could also make up your own. So, go ahead and read this it says, "The full hamburger moon crosses your ruling planet. You will have a strong urge today to enjoy a meal around noon. You will then either eat lunch, or not eat lunch and be very hungry.". So you can type that out or if you want to type --- shorten it or something like that, feel free to do that as well. So we have our first case, we have the code we want to run, and then we're going to break out of this. So now we can come in and specify our next case. So I'm going to go ahead and add another sign here. So let's say that the case is "Virgo". We need our colon and then we're going to alert our fortune. And then we need that break keyword once again. I always like to go ahead and add my break keyword from the start because it's really easy to forget that when you're creating a case. So let's see, I'm going to go ahead and copy another example little fortune here. So I'm going to say, "Your emotions will make you feel things today", which is a very insightful horoscope. Now we can come down here. And I'll just add one more so we don't have to type a whole lot. Let's say, "Leo". We have --- and then we'll just have another alert here. (Typing) And then we'll add that break keyword. (Typing) And then I'm go ahead and Copy another fortune that I wrote out and just Paste it in right here, just another little string, that you can read that in there. And then the last thing we want to do --- let's say that's all of the signs we want to list, is we need to provide a default case in case one of these is not true. So if sign doesn't equal "Taurus", "Virgo", or "Leo", what do we want to happen? So that's called the default. So we can use that default keyword, and then whatever we want to happen. So we want to say maybe, alert "Please enter a valid sign". And then the last thing we want to do is go ahead and break out of our switch statement, which I only added three of the signs here so if you want to get practice typing in this syntax by adding more cases with more astrological signs, I certainly encourage you to do that to get practice typing out the syntax since it is a little bit different here. So the last thing we can do is test this and I might improve this just a little bit by having a little bit of text, after it asks us --- it says, "Sensing (Typing) sensing your future.", something like that. So let's go ahead and test this. I'm going to run our code. It's going to ask us our sign and let's say we're Leo. It's going to tell --- give us our little message. And then it's going to run the code under that situation. So this is really really cool. You can see it's really similar to an if else statement in which it checks that condition and runs whatever code if that condition has been met. It's just slightly different syntax and you might find it easier to type this in then multiple if else statements. If you feel more comfortable writing if else statements still, then that's completely fine as well. So we get our little message here, and we can press OK. Now if we'd have forgotten one of the break keywords; it's very very easy to do that. Let's go ahead and take a look at what happens. So I'm going to go ahead and delete that out, our break keyword for our case "Virgo". So I'm going to go ahead and run this with that condition. So Virgo Enter, OK. And then it's echoing out our little fortune here. And if we press OK, you can see that when we forget that break keyword it's actually going to go and run the next case as if it were true. So it's really really important to remember have that in there. So we get our second fortune. I'm going to go ahead and press OK, and go ahead and add that back in. And you can see how using our switch statement we can create some really cool, really interesting things, like we just created our own little horoscope checker or fortune teller here, which is really really awesome. And if you want to come in here and add additional cases like I mentioned before, I really encourage you to kind of have fun with this. And just get practice adding multiple cases and seeing what happens here. One thing we might want to watch out for is if we type something in lowercase, so let's say I type in taurus lowercase, and you can see it has an uppercase T here. It's going to treat this exactly how it appears in our string. So we're going to get our default, it's not going to recognize that. So one little way we can fix that is by changing these two lowercase. So I'm going to change all of our capital letters to lowercase and we have a really cool little command here that we can use that's called, toLowerCase. So we can say, toLowerCase and that's just a period. And a lowercase t, uppercase L and uppercase C. So this is camel case and then we need parenthesis. So what this is going to do it's going to take the result or the answer we enter into that text box And it's going to convert that answer to all lowercase letters. That way no matter if we type an uppercase letter or a lowercase letter then we're still going to get the correct results. So if I run this now and I say, Virgo. So this is capital V and it's lowercase v in our switch statement. If we press OK, we get our little message and then we get the correct response. So it's converting that capital letter to a lowercase letter, which is really really cool. So now that we've taken a look at switch statements in an example of the kind of things we can do with them, in our next lesson I want to take a look at loops and learn about using a for loop for more control flow.
For Loops
In this lesson we'll learn about loops or another form of control flow. In our last lesson we talked about another form of control flow or switch statements, but now I want to take a look at a different kind of control flow and what's called a loop. And these are some of the most useful pieces of codes. They are incredibly common and they're very very helpful and allow us to do some really neat things. So let's go ahead and take a look at these. And what a loop does is it actually loops through a block of code until an original condition is no longer true. And just like with anything it's hard to understand without seeing it, so let's go ahead and take a look. So I'm going to go ahead and hover over this little button here so we can kind of preview this syntax. And what this is doing is we have another keyword just like with a lot of our common types of syntax. And this one uses four and then we have three things we need to specify in parenthesis. And you can see they're separated by semicolons. So we have three little pieces here. And those three pieces are an initial expression. So we're going to initialize our loop here by telling it where we want to start. So we're going to start with a value. In this case, we have 0, and then in our second piece we're going to specify the conditions. So our code is going to run while this condition is always true. So we're starting at 0 and while i, our variable is < 11, it's going to continue to run everything inside of this block. A block being anything inside of curly brackets, that's referred to as a block of code. And then our final piece here for our loop is an update to the initial value, because if we don't have this eventually evaluate to false then we're going to create what's called an infinite loop, and we'll take a look at that in just a couple minutes. And then of course, we put any code we want to run in our loop inside of that block. So let's go ahead and create our own and we're going to create just a very common kind of loop that's going to loop through and print a range of numbers. So we want to use that for keyword. So I'm going to say for, and then we need our parenthesis. I'll go ahead and press a space here so we have a little bit of room. And we want to initialize our loop, which you saw here it says, i = 0. This is what's going to create what's called a global variable, which we'll learn about in our next volume. But for now just know that you might see this syntax, but we want to use the var keyword because this is creating a variable essentially. So we're going to say var i = 0. So we'll start our loop at 0. And then let's say we want to print the numbers 1-10, we're going to say while i, lowercase i, is < 11, which you might think 10, but we'll take a look at this in just a second to see why we need to do 11, while i is < 11, we're going to increment i. This little ++ is a shortcut here. i ++ just means we're going to add 1 to that value. So we're going to say, i ++, so just a little new piece of handy syntax there. And then we'll add our block inside here. So while this is happening let's log what i is to the console so we can see what it's actually doing to all these little values here in our initial code. So we're going to say console.log, oops I forgot my period, console.log, which is going to print it to our Console down here so we don't have to push alert every time, that can get kind of old. So add our semicolon and let's go ahead and run this and take a look and see what is happening. So I'm going to go ahead and pull up our Console here and clear all this reflow stuff, which is happening every time we have a change on our page. You can see we get some information. So we're going to clear that, and now let's go ahead and Run our loop. So you can see we have 0-10 printing to our Console. So what this is doing is it's starting at 0, and then it's going to log 0 to our Console. And then after through once then it's going to come in here and now it's going to add 1. So it's going to check here. It's going to say, is it still < 11? If so increment it and log it to the Console. So we get 1, then it takes 1 and does exactly the same thing. So it has the effect of counting all of these numbers out. So you can see if we have said, i is < 10, which is kind of a common mistake here, it's going to end at 9. Or if you want to say < or =, you can say <=. So whenever operators here, our logical operators, and if we Run this we get the exact same thing. So it's just whatever is easiest for you. You can say < 11 or < or = 10. Whatever seems most logical for you since you're the one writing your code. So what happens if we don't have a condition that makes our loop fall? So let's go ahead and take a look and see what happens if we were to have this run forever, because if it's never false it's just going to continue running. So I'm going to say, for var i = 0, while i is >= 0. Let's increment i. So since it's starting at 0 it's always going to be > or = since it's just going keep incrementing it. So if we Run this you can see we have nothing happening. And now we get our little --- our little time guy, hourglass, and you can see that we have an Unresponsive script warning. So what we've done is we're creating an infinite loop and we're going to crash our browser when it runs out of memory. You can see we keep on, it's trying, it's really struggling to keep on running this. So we can just say, Stop script, and it will stop our script. So that's why we always want to make sure that when we're writing this we want to be really careful and check through this and make sure it will evaluate to false, because while it can be fun to crash our browser, we don't really want to do that. So, now that we've taken a look at for loops, in our next lesson we're going to get more practice using loops by revisiting FizzBuzz our exercise from Volume 1.
Revisiting Fizzbuzz
In this lesson we'll get some more practice with for loops by revisiting FizzBuzz. In order to get more practice with everything we've learned so far, I want to revisit an exercise we did in Volume 1. If you remember, we did a coding exercise called FizzBuzz. I want to try a more complex version, which is the version that's actually used in interviews and as a coding exercise. Which if you don't remember from Volume 1, in lesson 10 we did the following exercise, which was a simplified version that tested what we knew up until that point. So now that we have additional things in our JavaScript tool belt, like for loops, I want to go ahead and revisit this exercise. So what we're going to do is we're going to print all numbers from 1-100 with three exceptions: if the numbers are visible by 3 we're going to print fizz, if it's divisible by 5 we're going to print buzz, and if it's divisible by 3 AND 5, print fizzbuzz. Which if you feel comfortable like you already know how you might try this yourself, I encourage you to pause it and give it a try before continuing to watch or if you just want to watch me solve it, that's completely acceptable as well. Coding is very challenging and you really have to rewire your brain to start to think in a new way, to start to think using code. So to get started we want to break this down into manageable parts, because if we just try this from the start we're probably going to fail because it's really hard to dive in without starting small, starting manageable. So I want to start just by printing all numbers from 1-100. So if you can remember in our last lesson we were able to print the numbers 0-10 using the following code; we used a for loop. So modifying this we can just do it a little bit differently and get the result of printing 1 to 100, instead of 0-10. So I'm going to go ahead and start our for loop. So I just want to use that for keyword, and then in our parenthesis we need three parts. The first thing we need to do is we need to initialize our loop with a variable or tell our loop where it needs to start. So we need that var keyword to create our variable. And we're just going to call it I, it's kind of a common convention, but you can call it anything you want as long as it follows that naming convention for variables. So we can't start our variable name with a number or anything like that. So we're going to use var i = 0, or excuse me 1, because we don't want it to print 0. So we're going to start at a 1, then we need our semicolon and we need to set the condition under which our for loop is going to run. So just like for our for loop for our last lesson, you can see it says, i is < 11. So if we want it to go to on 100 we just need to + 1 so it stops at 100, so we want it to stop at 101. So we're going to say while i is < 101 or if it makes more sense to you, it's easier to think of it < or = 100, you can certainly do that too; whatever makes sense for you. So I'm going to add that semicolon, and then the last thing that we want to do is we want to update our loop every time it runs. So what do we want to happen to our code here every time it loops through? So since we want it to go up by 1, we want it to have every number from 1-100 printed, we just want to increment it by 1 every time. So we can use our little i variable. And if you remember from our last lesson we learned how to increment a variable or a value using the increment operator, and that's just ++, which means increment it by 1 every time this is Run. So now we just want to add our code block with our curly brackets and add all of our code inside. So since we're just going to start by printing all these numbers, we're just going to say, Console.log our variable i. So let's go ahead and test this out. So I'm going to clear the Console and let's go ahead and Run our code and take a look. And if you see here you can see we have 100 is the last thing that was run. So we have it ending at 100 and if we kind of go back in time to see how our loop was running, you can see that it's going down by 1, meaning every time it's running through it's adding 1 since we're going backwards here. So if I scroll all the way up here you can see that we start at 1, and then every time our loop runs it adds 1 and then ends at 100. So this is perfect, we've done the first part of our exercise, meaning we can move on to our next little piece. So now we want to say, if the number is divisible by 3, print fizz. So, it might have been a while back for you. If it's been a while since you watched Volume 1, but we learned how to check if a number is divisible by another number by using that little percent sign, which is called modulo. So right on top of here --- inside of here we want to add an if statement. So we want to check if a condition is true, then do this. So it's perfectly acceptable and in fact, necessary to embed different pieces of syntax we know in order to create a new combination so it does exactly what we need it to. So we want an if statement to run every time our loop is running as well, so we can just put it inside to get that effect. So inside of here I'm going to say, if our number, so i, is divisible by 3, so we're going to use that modulo, and then 3. So this is going to divide it by 3 and return a remainder. So if we want to check if it's divisible by 3 it will have 0 leftover after it's been divided by 3. So we can say if the remainder of our variable divided by 3 is = 0 then do the code inside of our curly brackets or our blocks. So what do we want to happen if our number's divisible by 3? We want to print fizz. So we're going to say, console.log, oops if I can type correctly, a string, which is going to say, "fizz". Then add our semicolon and then otherwise we need otherwise we need our l statement. So we could say otherwise, else, just log our number to the console. So I'm going to Control + X to Cut this and Paste it inside of our l statement. So now we can test this now that we've added the next piece of our code to this. So we're going to run through a loop, we're printing all the numbers 1-100 to our console and if it's divisible by 3, log "fizz", otherwise just log our number. So I'm going to go ahead and clear this so we can test this out. And you can see once again we're ending at 100. And then we have 99 and we see "fizz", instead 99 is divisible by 3. So that looks good. If we go back three, we can scroll up and you can see that everything is now printing "fizz". So very, very, very cool. We've done the first step here in our problem. So now we can move on. We can also check if the number is divisible by 5 and then print something else. So to do that we can add an else if statement to check for multiple ifs; if you remember from Volume 1, so I'm going to press Enter to bring our else onto a new line. And then we can just say, else if, check for this condition. So we're going to say if our variable's divisible 5, then our triple = to 0. So if we divide it by 5 and the remainder is 0, same thing is divisible by 5, then I want you to console.log "buzz". So we're going to say, console.log and then our string, which is "buzz", add our semicolon and then otherwise just log our number to the console. Which --- you'll see if l statements written multiple ways. You might see another condition starting on the same line as this curly bracket or sometimes people just press Enter and break it onto a new line. So whatever is easiest for you to read, I would definitely do that. So I'll just go ahead and keep this consistent and start this on a new line, just like our lf --- else statement. So let's go ahead and test this and Run our code. So I'm going to clear our Console and we're going to Run this. And you can see now instead of 100, we're seeing "buzz" since 100 is divisible by 5. So we should be able to scroll through this and kind of check. So we have 95. Where that would appear we have "buzz". So looks pretty good. We have 85, we have "buzz". So it looks like we have the first two parts of our code now working. So very very cool. Now we can move on to our last part to check if the number is divisible by 3 and 5. So if we're thinking about this using what we know, it makes sense to add another else if statement to check to see if it's divisible by 3 and 5, but I'll kind of write this out and show you why this might not work for us. So I'm going to say, else if and we might say, if our number is divisible by 3, (Typing) and if you remember we could use the and operator to check for multiple conditions using double ampersands. So this means and it's divisible by 5. (Typing) Then we want to console.log "fizzbuzz". Oops, and I added a 9 instead a parenthesis. So I'm going to go ahead and fix that. (Typing) Then we just need our semicolon. And while at first glance this makes perfect logical sense, if we go through and think out our code it's first going to check and --- check if it's divisible by 3, then 5, and then lastly 3 and 5. So if a number is divisible by both it's going to print "fizz" then "buzz", and "fizzbuzz" as well, which is not the results we want. So this is very very close to what we want. We want to first check to see if it's divisible by both. So rather than writing it like this, we can do something a little bit different. And we can add another if statement inside of our first if statement. So, I'm going to delete this and I'll kind of go through why we do this way. If it's divisible by 3 then we add another if statement, we could say if it's also divisible by 5 do this, otherwise you can --- if it's only divisible by 3 just continue to print "fizz". So we could say, if that number is divisible by 5 (Typing) then we want it to console.log "fizzbuzz". (Typing) Otherwise just go ahead and log "fizz" since it's only divisible by 3. So I'm going go ahead and clean this up a little bit and then we can just go through this just one more time to make sure that we can see what's happening here. In our first if statement, as it's running through our loop, it's going to check to see if it's divisible by 3. And then it's going to do everything here inside of our 5th first if block, which you can see ends right here. So it's going to check first to see if it's also divisible by 5 then it will log "fizzbuzz", otherwise it's going to log "fizz". So if it's divisible by 5, it's going to not run this first condition since it's not true. And then it'll just check here and see yes, it's divisible by 5 and then log "buzz", otherwise we still just get our number printed to the Console. So I'm going to go ahead and delete these extra spaces and now let's just go ahead and test our code. So I'm going to clear our Console and then we're going to go ahead and Run this. And let's go ahead and find a number that's divisible by both. And you can see we have 90, which is divisible by 3 and 10. And we're getting "fizzbuzz" and we're not getting multiple words, so it's not saying "fizz" and "buzz" and then "fizzbuzz", which would have happened if we hadn't have thought through that and fixed that a little bit. So if we go here and scroll we can see we have 75, which is divisible by 3 and 5. So we get "fizzbuzz" there. And there we go; we've solved a fairly complex problem when we're learning and gotten the results we want. While stuff like this can seem really overwhelming at first, you'll see you can do so much more once you take it one step at a time and just test your code as you go long. So now that we've kind of practiced our for loops and combined it with if else statements, in our next lesson we're going to learn how to use another loop called, do while.
While Loops
In this lesson we'll learn about two loops that are similar to for loops. Now that we've had some more practice with for loops, I want to take a look at an example of two additional types of loops that we can use that are very similar. And these are called do while and while loops. The first one I want to take a look at is a do while loop. So I'm going to go ahead and hover over our syntax example here, and you can see the code right here for our do while loop. We have two keywords, we, just like in the name have do and then we add a block of code, which we store the code we want to run and then we run that code while that condition is true. So do this while this is true. So just like with everything, else we need to type it out to practice this to be able to truly understand what it actually is doing. So over here I want to compare this to our for loop and just do exactly the same thing we did two lessons back by printing the numbers 0-10 to our Console. So for our do while loop we need that do keyword first. So we can say, do and then we need our code block here, and right after this we can say, while the condition in our parenthesis is true, and then we need our semicolon. So if we want to do the same thing as our for loop, we first want to start by logging our variable here to the Console. So inside of our do block here we want to say, console.log, our variable. So let's just use i, just like we did with our for loop; so just log i. And now that we've used that we don't have a specific place to declare our variable or initialize it like we do with a for loop. So we want to declare our variables always before we use them. So I'm going to add a space up here. And we'll start by creating the variable we're going to use. So we want to say var i, and then we can give it an initial value. So let's just set it to start at 0, just like we did in our for loop. So we want to log our number --- if we want to print the number 0-10, while i is < 11, we want to log that to the Console. So we could say, while i is < 11. And if you look at this right now you can see we have our initial variable starting at 0, it's going to log i. So whatever value stored in there, while it's < 11, but right now we have an infinite loop because we aren't changing this or nothing else in our code is changing it either and it's always going to run, meaning we're going to have our little infinite loop here. So right underneath this in order to make this eventually evaluate to false, we want to update that initial value. So let's say i ++ and then add our semicolon. That way every time it runs through our loop it's going to increase its value. So I'm going to go ahead and clear our Console and we can run this and see what this does. So I'm going to go ahead and press Run. And you can see we're ending at the number 10. And if I scroll up here you can see we started at 0. And just like with our for loop, it's adding 1 to our variable every time we run through our loop. So we're starting at 0, and it's saying log 0 then add 1 to our variable. And while that's still < ll, continue to do that so as effective counting it by 1 every time it runs through our loop. And our other loop, our while loop, is very similar to this. So right underneath here let's go ahead and get some practice with that syntax. And rather than having two keywords, if you look over here we can kind of get a hint. You can see our while loop just uses the while keyword. So we're saying, while this condition in parenthesis is true, and then we open and close our curly brackets, and we add whatever code we want to run inside. So we can say, while this condition is true, in our parenthesis, do this. So very similar logic to our do while. And if we want to accomplish exactly the same thing, we can say while i is < 11, I want you to log it to the Console; so console.log i. And then just increment the value so we don't get our infinite loop here. So I'm going to comment out our do while loop here so we can run this and then we can take a look and see what the difference is. So I'm going to comment this out with our multiline comment. You can see here we have our / then our * and then our * and our /, just like we would do in CSS. And then now we have our while. So I'm going to clear our Console and Run this. And if you take a look over here you can see we're ending at 10. And if we scroll up we're starting at 0 and incrementing by 1 every time our loop is run. So we have the exact same end result as we did with our for loop and our do while loop as well. So at this point you're probably asking yourself what is the point? Why would I want to use some of these loops in some in cases or rather than other loops in some cases? So let's take a look at that. I'm going to go ahead and uncomment our do while loop. And to kind of think through the logic and see how these might be different even though they have the exact same effect, we can start by thinking that our code, and remembering that our code is being read from top to bottom. So we have our initial variable here and then in our do while loop it's going to say, do this, and it's going to run this code. And then it's going to see our condition, while i is = 11. So the effect of this is that it's reading the code that's going to be executed first. So this loop is always going to run at least once before checking the condition. And if this condition is found to be true, it'll continue running. So if we compare it to our while loop, it's checking the condition first. So starting here it's saying, while this is true and if this is immediately false it never gets to this part and it will never run. So this will only run if that condition is ever true our do while loop will always run at least once. So a little bit confusing there, but if we slow it down and try to think it through, hopefully that makes a little bit of sense that it's going to see this first before it ever checks our condition. And if we compare this to our for loop, maybe you're asking yourself why would I use do while or while over a for loop? A for loop is useful when you know how many times you need your loop to run. Do while and while are more useful if we don't know exactly how many times our loop needs to run. So we can just say, while this is true, do this. I don't when or how many times this is going to occur, but I want this to happen no matter how many times this condition is actually true. Which is hard to think about and understand when we're not using this in context or we're not writing our own code. So it'll start to make more sense as you go along and use it in code of your own. So I want to take a look at another example of a while loop, kind of a more fun example. So that's in our project files. I'm just going to go ahead and open file. And in our lesson 05_begin folder, we also have a scripts folder. So I'll go ahead and show you. We have this scripts folder and then we have cheerup.js. So I'm going to press Open here. And it's going to ask us if we want to save our changes, so you can Save it if you want. Maybe we want to save it with our other files so we can come back to it. I'm just going to call it practice.js. And then it will load our new file. So I'm going to go head and Run this so we can see what this is doing, and then we can go through the code because it looks like there's a lot here and this is a bit more complicated than anything we've done so far. So I'm going to go ahead and press Run. And what I've done here is just for fun, kind of created a silly script called, Therapy, the JavaScript Care Robot. And his job is to cheer you up and to make you happy. So we get this little message here asking us if we'd like to be cheered up. So we can press OK or we could press Cancel. And if you're wondering why maybe this doesn't say yes or no, there is no way to change these default values unfortunately, from OK and Cancel when we use something like confirm. So we're kind of stuck like this. And even though it's not perfect we can still kind of work with what we have. So would you like to be cheered up? We could say OK. And then it's going to tell us a little joke. So we can read through it and laugh hysterically or if we don't think it's funny I guess we don't have to laugh either. Then we can say OK. And then it's going to ask you if you want to continue your session with a therapy robot. So we could say OK or we could also Cancel to exit out, but I'm going to say, I'd like to continue our session. And then it's going to ask us to tell therapy your troubles. So we can type our feelings, like I can say maybe, I am sad because I am hungry; a little sad face. And then you could press OK. And then we get our nice little message. He's going to comfort us and give us a nice big computer hug and we can press OK. So going through this, I know this is kind of silly, but this is another example of where we could use a while loop with something other than numbers and other than a situation in which we have a value that's going to be incremented like, i is < 11, or i is > 11, or something we've done up to this point. So let's go ahead and take a look through this. And the first thing we're doing is we're using our confirm box, which has OK or Cancel. And every time we use a confirm pop-up box like this, if we press OK, it's going to return true to our code. So if we press OK as a result of our confirm, it's going to restore true and our variable. If we press Cancel it's going to return --- oops I put no, but that's false, it's going to return false. So we say, Cancel it's going to return false. And our while loop, which is checking to see if this is true, will never run. If it is true you can see this might be kind of confusing, while sad, while variable, but this is exactly the same thing as saying, while sad is = true. So just kind of a little bit different way to think there. So while sad is true, we're while sad. It's going to alert our joke, and then it's going to ask us a question, would you like to continue? So we can say OK or Cancel, and it's going to store the result in our variable. So if our variable is true it's going to run everything inside here and then set sad to false, so it's going to set our initial variable to false and our while loop while quit. Otherwise we're going to set sad to false as well, and it'll exit out of our loop so we don't create that infinite loop. So I know this is a lot and I don't expect you to understand this right off the bat, but if we think about this slowly and play with it and test different things, it starts to make more sense. I just wanted to show you a different example that's completely different from anything we've used this for. I would never expect you to be able to create this after just writing one yourself. So down here I just have one more example as well, in kind of a more practical example. Maybe something we might actually see on a website where maybe we have a variable userLoggedIn and we set it or initialize it as false. So when someone first visits a website and there's a login area, they're not automatically logged in so it starts at false. But if they logged in, so while this is true, while the user is logged, maybe we have something else in our code that sets this true, after the user does login then it's going to display our login info. Obviously, if we use this code on a site it wouldn't work because we need a lot more to make this work, but I kind of wanted to put in plain English so we could see maybe a more practical use of a while loop as well. So now that we've gotten more practice with loops and taking a look at do while and while, in our next lesson I want to switch gears a little bit and learn how to use functions, which are awesome and allow us to perform actions and commands in JavaScript.
Functions
In this lesson we'll learn how to create functions. Let's say we've created the following friend with CSS named Mark, and we want to greet him using JavaScript. Using the code we know so far, how do we accomplish this? One thing we might do is create a variable and give it a name. So let's say we call our variable name. And then we store the name of our friend so we can remember it, something like "Mark", as a string. Then to greet our friend we might use a command like, alert or console.log, just to use that. And then we might say something like, "Oh hi" (Typing) and then our friend's name, so referring to the variable. And maybe we'd also put a space in there, that way so there's a space between our string and then the name. So if we were to Run this we'd get something like this. So you'd have our greeting, "Oh hi Mark". And then let's say we have another friend that shows up. So maybe Lisa comes over. How could we also greet Lisa as well? Well maybe we'd create another variable to remember her name. So we'd call it something like var name2. And then we'd store her name as a string; so "Lisa". And then we might also console.log, (Typing) and then our greeting. (Typing) And then our reference to our second name here. Then when we Run this we get the following and we greet our first friend "Mark", and then we'd also greet our second friend "Lisa". Well what if we had another friend come over? Say we have "Denny" who joins our party here, and we want to greet him as well. Well, you can see if we're repeating the same action over and over it can get very tedious to write the same lines of code over and over again every time you need them. So how could we clean-up our code and be more efficient with our JavaScript? Well, one thing we can do is create what's called a function. And a function allows us to do just what its name implies, it helps us perform a function or an action and it associates that with a named command. And we've also been using functions all along without realizing it. So when we say something like, alert and then we pass it "Some text". (Typing) When we Run this our alert is actually a function. We're using a command and then we pass some --- some information inside of parenthesis that do something associated with this command. So if you take a look at console.log, that's another example of a function. We have a command that has a name, so it's named something like alert, and then we do something with the information we're passing it inside of those parenthesis. So thinking in terms of this, let's create our own function that will greet our friends so we don't have to repeat all of this code. So I'm going to go ahead and delete all of our code we've written. And to create a function we can use the function keyword. So we can type in function and then we need to give it a name that makes sense. So just like alert will create a pop-up that alerts some information. Maybe since we're saying hello to our friends we might call our function something like, sayHello. Next, we need our parenthesis and we need to put the information our function is going to expect inside of the parenthesis. So when we alert it expects something like a string. Here when we use a greeting, our sayHello function, it might expect something like a name. So we're going to use that as our parameter, that's what you call the information inside these parenthesis. So we're going to say, sayHello with a name. And then we need some curly brackets, as well. And we're going to put a block of code in here or any code we want to run every time we use this command. So for example, when we use our function sayHello, maybe we want it to just console.log our greeting. (Typing) And then we'll just use the name that we pass to our function in our code. So we'd say, "Oh hi" + name. (Typing) And then now we can use our function. So we can use that function's name and then we just need to pass it a parameter. So inside of our parenthesis let's say we want to greet Mark, which I'm going to go ahead and clear out our Console. We could just put "Mark". (Typing) And then we can Run it. And now it's going to say our greeting, "Oh hi Mark". And maybe if we just want to greet Lisa and Denny, all we have to do every time we want to run this code is we just have to use our command and then the correct name. So if we want to greet Denny we could just pass "Denny" to our function here. And now if we Run it you can see we have our greeting three times, and our code is now much simpler, it's much cleaner, and we don't have to retype that same information every time we want to perform this action or this sequence of steps inside of our function. So now that we've learned a little bit about functions, in our next lesson I want to continue talking about functions and taking a more in-depth look at the syntax and also get some additional practice.
Additional Practice with Functions
In this lesson we'll get additional practice using functions. In our last lesson we learned how to create a function using the function keyword, we gave our function a name, we gave it any parameters we needed, and then we added some code inside of our code block or curly brackets. So we created our function, we named it sayHello, which takes a name as its parameter, and then it passes that name and inserts it into our code wherever it finds that name word; just like we would use a variable. Then to actually use our function we just need to call it by name, which when we use a function it's commonly called, calling a function or invoking a function, and then we passed it an argument in parenthesis. So just a little bit of a note here on terminology, when we create our function we call the part in parenthesis a parameter, and when we actually use it we call it an argument. So when we're right here using our function, we'd say we're calling sayHello and passing "Mark" as the argument to our function. So I know there's a lot of terminology and new words to learn here, but kind of try to remember that little difference between parameters and argument, and also when we use things like calling a function. Now what happens if when we're using a function like this we forget to pass it an argument? So right below here, let's go ahead and test that. So I'm going to use our function sayHello, and then I'm just going to leave that little part blank there. So I'm going to Run our code and we get the following: we get our first one, which passes "Mark" as our argument. So it's going to say "Oh hi Mark". We get the same with "Lisa", same with "Denny", and then for our last one where we didn't pass it an argument, we see undefined. So if you think back to Volume 1 we learned that a value type possibility is undefined, meaning JavaScript doesn't know what you mean because it hasn't been defined for it. So it's returning undefined as the argument we passed to our function. So when we forget to use an argument when it expects one, then we get that little message and we want to be very careful about that. Which if you've forgotten what your function expects, maybe you didn't write a function yourself or you wrote it --- one a long time, it can actually kind of tell what it expects to see. So let's say if I type in sayHello, and then add the parenthesis, you can see we get a little hint here with our function name. And then it's saying it expects a name, we see our parameter here, and we also see what type it expects, as well. So it's going to expect name, our parameter, and it's going to expect that to be a string. So if we use something like alert and add our parenthesis, that's exactly what that is as well. So it's expecting a message as a parameter and it also expects that to be a string. So this is a really cool thing we can do to kind of see what it expects to see and we kind try to do the right thing. So I'm going to go ahead and delete this all. And we can get additional practice with functions. And let's take a little bit more practical example; maybe we're trying to calculate the area of a square. Well the first thing we need is that function keyword. Then we need to give our function a name that makes sense. So let's say, calculateArea. (Typing) And then we need to pass it our parameters, or create our parameters. So I'm just going to leave this blank for just a second, add our code block, and let's say when we calculate the area of a square we can say that it's going to be width * height. But since we know a square has the same width and height then we just need one side. And we can say maybe just return side * side. So since they have the same we're just going to multiply that --- or square it; so side * side. And now we know exactly what we need our parameter to be. So it's going to expect us to tell it what that side length is. And then it's going to pass that to our code. So now to use this we can just call it using the name. So we can say calculateArea. (Typing) And then let's say we want to calculate the area of a square with a width and height of 5. Then we could just run our code. But you might have noticed that nothing happened here over on a page and that's because when we use a function we all --- don't always have a visible result. Maybe it's just calculating a value and passing it somewhere else in our code, then we aren't going to see anything happening. So if we want to be able to see the results of this we need to use something like console.log or alert to be able to visibly see what is being calculated by our function. So maybe right here we'd want to say console.log, (Typing) and then whatever we want to log to the console in parenthesis. And now if we Run this then we can see it's calculating the area of our square. So if we had a square with a something a little bit more complicated, (Typing) and maybe if something crazy like this, then we can just run our code, and you can see it's going to calculate the area for us. Now if we wanted to make this a little bit more complicated, maybe we would want to calculate the area of a rectangle. Then we can just modify this a little bit and we could do that as well. So I'm going to go ahead and delete that. And if we're calculating the area of a rectangle instead of side * side, we're going to have sides with two different lengths. So maybe instead of side and side we can say maybe, side1 and side2, or maybe width and height, whatever you prefer. And then now that we need multiple pieces of information we can actually list multiple parameters despite commas separating them inside of our parenthesis. So right here we can say side1, side2. And now our function is going to expect to see two arguments when we call it. So we can just use calculatArea. (Typing) And then in parenthesis instead of passing it one argument we can just say maybe we have a rectangle with one side that's 10 long and another that's 40 long. We can just add those as a comma separated pair. So the first argument it will pass 10 as that parameter. And then for our second argument 40, it will pass that as our side2 parameter. So we can go ahead and Run this and you can see that we're getting 400 as our result. But we aren't always going to have parameters when we create a function. Our parameters are actually optional, meaning we can create a function and we can leave this blank. So let's go ahead and take a look at this. So I'm going to delete our little function there. And let's say we want to create a function that generates a random number. So maybe we'd use our function keyword, and we'd say randomNumber. So it'll create a random number for us every time we call this. And if we just need a random number it doesn't really make sense to have a parameter. So we can just add our parenthesis and leave it blank. (Typing) And then we just need to add our code inside our curly brackets. So let's say we want to create a random number, we could use that Math.random command. And we add our parenthesis and then our semicolon. Which just a fun note, this is also a function as well, which we kind of saw here, it's going to return a number, this little guy, this little arrow right here means it's going to tell us what type of value our function is going to return. So if you want to see this we can say console.log, a randomeNumber, and now every time we need a random number we can say randomNumber. We can leave our argument blank, and then every time we Run this we'll get a new random number. So very very cool. You can really see from this how dynamic and how flexible functions can really be. They save us a lot of work and a lot of typing, and make our code more clean and elegant as well. So now that we've gotten some additional practice with functions, in our next lesson we're going to learn about something else that's incredibly useful called, an array.
Arrays
In this lesson we'll learn how to create an array. What if we wanted to store a list of our friends we created back in lesson 6? Well, how could we do that using something other than multiple variables? One thing we can do is create something called an array. An array allows us to store a list of information. So it's perfect for a situation like this, in which we want to store multiple pieces of information or multiple values. Maybe we wanted to create something like a contact list and have a list of friends to reference later in our code. This would be perfect for this kind of scenario. So let's go ahead and take a look at this. And to create an array we first need to remember our array, or store it, in our code using a variable. So we use that var keyword, then we need to give our array a name. So maybe we want to call it something like, friends. And then we need the assignment operator, our = to store our array. So the syntax for an array is straight brackets, like that. Then we can add our semicolon and that's all there is to creating our array. So if we want to see what this does we can press Run. And in our Console we can call our array. So we can say, friends. And then you can see we have our empty array, meaning we have no friends. So, let's go ahead and fix that and add some values to our array. One way we can do that is to add our values immediately to our array when we create it. So inside of these brackets we can add whatever information we want separated by commas. So we can add our first friend, maybe "Mark". Then we can add our friend "Lisa". And then we just need another comma and then we can also add our friend "Denny". So if we Run our code. And now if we call our array you can see it's returning an array, and then it also gives us our comma separated list of values in exactly the order we added them to our array. So what if we wanted to reference a position in our array in our code. We want to reference a specific friend in our list. Each one of these is called a position, so as a position in our array. Well, we can use some syntax for that as well. So if we want to call Mark, maybe we would do something like friends and then our position. So if we're putting it over here, we need to tell it to echo it in our Console, so we might say console.log. And then our friends and then the position we want to call in our brackets. So if we Run this code you can see it's returning "Lisa". So that's kind of weird. We might expect Mark to be the result when we call the first position in our array, but arrays do something kind of funny; and that's that the array's position starts at 0. So if we wanted to reference "Mark", instead of calling 1 we actually need to put 0 in as the position. So if we Run this then we get "Mark" as the result. So since "Mark" is 0 and "Lisa" is 1, as you might expect if we put in 2 as our array position and Run our code, then we can get "Denny" as our result. So what if we want to add additional information to our array after we've created it? Well we have a couple different ways we can do this. So I'm going to go ahead and delete our position here. And one thing we can do is we can reference our array. So we can say friends and then we need to tell it what position we want to add it as. So maybe if we want to add it as our third position, so 0, 1, 2, and then right after "Denny" we can say 3. And then we use our assignment operator or =, and then we can add whatever name we want. So maybe we want to use "Bob" as our name. Then we could Run this. And now if we ask it what the third position in our array is, we can use that same syntax, so we can say friends tell me the third position in our array. And you can see it returns "Bob" as the third position in our array. And just like with some other things, we have functions that do things specifically with arrays as well. So just like we have console.log, which has a function associated with our Console, we have commands for our array as well. So if we want to add a value to our array and we don't know the position, we can use what's called the push function. So if we say, friends.push we can add some information inside our parenthesis. We can add our argument. So you can see although it expects a number, we can do a string or whatever we want because luckily we are using a language JavaScript, which is incredibly flexible. So if we want to add another friend, maybe we want to add "Mary". We can say push "Mary" to our array. And if we Run this and then ask our Console what is inside of our friends array. You can see that now we have "Mark", "Lisa", "Denny", "Bob's" added as our third position, and then automatically adds "Mary" as the last position in our array. So now that we've created our first array, in our next lesson we're going to get some additional practice using arrays and also combine it with some other pieces of code that we've learned so far like functions and for loops.
Looping Over an Array
In this lesson we'll get additional practice with arrays. So let's say our list of friends has grown to include Peter, Steven, and Claudette. How could we easily greet all of our friends using the syntax we have learned up to this point? Well, we could create our function that took a name as an argument and pass it each name of our friend. But taking advantage of our array, how might we use some different kinds of code in order to greet all of our friends automatically without having to tell it each new person we add to our list of friends? Well, let's go ahead and take how we can --- look at how we can combine two pieces of code not only a function, but an array and a loop. So starting on line three I'm going to go ahead and create our function using the function keyword and give it a name. So maybe we want to call it greetFriends. And this time we're not going to give it a set of arguments, we're going to leave that blank. And then add our curly brackets so we can insert all of our code we want to run every time we call our function inside. So we have our list of friends. And one incredibly useful thing we can do with a loop is loop over an array. And this is a very common use of loops. So let's go ahead and take a look at how we could do this. So we're going to use a for loop, so we need that for keyword. And then inside our parenthesis we need those three pieces of information. We need to initialize our loop or give it a starting place and we're going to be looping over our array. So we want to start at the first position in that array. So if you remember last lesson we learned that an array's first position is actually position 0. So this is going to be where we want to start our loop. So we'll initialize our loop. And we'll just call it i again, and we'll start at 0. Then we add our semicolon and here our condition is going to be a little bit funny. We're going to take our variable and we're going to say, while i < the name of our array, and then we're going to use a function called length. So friends.length; and I'll go over what this does in just a second, and then our semicolon. And then the last thing we need to do is add our update to our loop that'll be be making a change to our initial value every time this loop is run through. So we're going to go ahead and increment it just like we've done before. So we'll say i ++ (Typing) and then we need the code we want to run inside. So every time we call our function we're going to be creating this loop, and then we're going to do everything inside. So every time our loop runs we're going to greet a new friend. So we'll say console.log. And then we'll figure out what we're going to put inside of here in just a second. So coming back to this, what this is going to do, if you remember when we created our loop that logged the number 0-11 to our Console, what this is going to do is it's going to essentially do the same thing. It's going to start at 0, which will be our friend "Mark" here, if we were to pass this to our array. And it's going to increment this, so it's going to go to 1. And it's going to increase as long as i < the length of our array. This function right here is going to return the amount of values we have in our array. So we have 1, 2, 3, 4, 5, 6. So it's going to say while i = 0, while i < 6 continue to increment i. So what we want to pass here into our Console is we're going to have our greeting. So let's say, "Oh hi", and then right here we're going to pass i as a position in our array. So we're going to take our array, friends, and then we'll pass i to it. And then let's go ahead and take a look and see what this does. I know this is confusing right now, but we'll continue to go over this in just a second. So I'm going to go ahead and Run this and I'll pull up our Console. And also we need to call our function so we see it. So we'll say, greet our friends. (Typing) And when we press Run you can see that we get the effect, which after I scroll back up right here, of its greeting every friend we have. So if we scroll down here we have all of our friends, and now we're greeting them one by one. And you can see this is much less code than if we had created our function sayName, and then passed every name as an argument. Furthermore, we can add as many friends as we want to our friend array and it's going to greet every single one of them no matter how many we add to our array. So this is very, very, very helpful, and also very cool as well. So now that we can see what this does let's go ahead and take a look at our function we created here and kind of reason through what it's doing. So we have our first part here. So starting at 0, it's going to check and see if 0 is < the length of our friends array. So looking through here, it is < our array. So it's going to pass 0 through here. And it's going to log "Oh hi", and then friends. If you remember, this syntax will return the position an array. So if we want to say friends 3 for example, it's going to start 0, 1, 2, and then it's going to return "Peter" as that third position in our array. So if we pass 0 through the same syntax, it's the same as saying friends 0. So it's going to say, "Oh hi" and then it's going to look in friends for the position 0, and it's going to return "Mark". Then since this is our loop it's going to add 1 to our value and it's going to check and see is 1 < the length of friends? If yes, we're going to say, "Oh hi", and then friends position 1. So this would change to 1 and it's going to return "Lisa". And then similarly it's going to add 1, so we're at 2 now, and it's still < the length of our array, and so it's going to pass in friends 2. So look in here 0, 1, 2, and now pass "Oh hi", and then return "Denny". So I know this is a little bit confusing and a little bit complicated to think of it first, and I wouldn't expect you to be able to write this on your own, but it's an incredibly useful piece of code and it's definitely worth remembering and learning. So I wanted to take a look. And also to see how we can use an array to do some very nice coding, some very elegant code that saves us a lot of work. So now that we've gotten some more practice using arrays, and also learned how to combine them with other pieces of code, like a for loop, in our next lesson we're going to take a look and see how we can create our first JavaScript file from scratch.
Creating a JavaScript File from Scratch
In this lesson we'll learn how to create our first JavaScript file from scratch. For this lesson we're going to switch gears a little bit and use a text editor to create our first JavaScript file. So instead of using Firefox and our Scratchpad for this lesson, we're going to use Brackets text editor or Adobe Edge code as another name for the same text editor. And I have our live preview of our project file for this lesson pulled up using the lightning bolt icon, which needs Google Chrome to run. So if you don't have Google Chrome, you'll need to download that. And if you don't have Brackets, you can go to brackets.io and download the newest version of Brackets, which is a fantastic text editor, it's open source and it's also free. So I'm going to go ahead and exit out on this. And once you have Brackets open you'll want to open our project folder. So just come to Open Folder and in our project files just make sure you click on lesson 10_begin, and then you select this folder. From there you'll just want to double-click to bring up our index.html file. And make sure you have the lightning bold selected so we can see a live preview of our file in Google Chrome. One very important skill we need to have is to be able to create a JavaScript file from scratch. Because when we start adding JavaScript to a webpage or something like that, we're not going to be able to create a scratchpad and save it in the browser, we're actually going to have to add it to our site files in our text editor. So the first thing we want to do is we want to create a folder to store our JavaScript files. Just like with our css files here, we store it in a folder called, styles. We need another folder for our script so we organize all of our files by type. We have our html files in our root folder, our css files in our styles folder, and then our scripts in our scripts folder. So I'm going to come and right-click and we can create a New Folder directly in Brackets. So I'm going to click on that, and then we'll name it scripts. From there we can create our first file. So we can actually right-click on our folder and press this first option to create a New File. It will add it inside of our scripts folder, and we can just call it main.js. We'll whatever we want to name our file as long as it follows this common naming conventions for the web. So I'm going to press Enter, and now we have our first JavaScript file. You'll just note that we need that .js extension, and that's all it needs to recognize that we're going to be putting JavaScript code inside. So let's say if we want to create an alert and say, "Hello World". (Typing) You can see it's just like adding code inside of our Scratchpad, the only difference is instead of writing Run every time we have to Refresh our page, which once I did that you can see that nothing happened. And the reason for this is we still need to attach our JavaScript file or link it to our html page. So I'm going to come back over here to our index.html file, and we can add it into places. We can add it in our head, which you'll see a lot, but one recommend practice is to add it right before the closing body tag. And the reason for this is since our code is read from top to bottom by the browser it's going to render everything else on our page before it loads our script. This makes our page load much faster. And in addition, if there's any errors in our JavaScript file it's going to render the content, the most important part of our page first, before it gets to our script. So with that let's go ahead and add our script. So I'm going to press tab a couple times until we have that nice line of indentation maintained. And then we can add it using a script tag. And we need two attributes inside of our script tag. If you aren't familiar with HTML, an attribute is any information added inside of an HTML tag using an =, and then we add whatever information inside of quotation marks. So we're going to add first a source attribute, that's src. And then we need to set it = to our file path inside of these quotation marks. So we stored it inside of our "scripts" folder. So we'll say, "scripts" and then our file name, main.js. The last attribute we need is the type attribute to tell our browser what kind of file it can expect to open. So we're going to use the type attribute. And we're going to tell it that it is text, and you can see right here text/JavaScript. Then we just need our right angel bracket, can see it has a closing tag, we have our script closing tag, and then we can press Save. And now when we refresh this, we press Refresh, whoops, make sure we Save our file here. Then you can see our alert. So we can press OK, and now we can add whatever JavaScript we want to our js file and then once again, instead of running it like we did in our Scratchpad, we'll just want to press Refresh. So now we can get used to using JavaScript in a way that's more practical or more used in a real-life situation. So this is how we're going to be writing our JavaScript from now on. So I'm going to press OK. And now that we know how to create our first JavaScript file from scratch, in our next lesson we're going to start putting everything together and taking a look at how we can create a plan for our code and then actually execute our code or our plan in the form of code.
Plan Then Create
In this lesson we'll start to put together everything we've learned so far in this course and also talk about the importance of planning before coding. Now that we've learned how to create JavaScript files from scratch we're ready to start creating JavaScript files of our own. But one thing I want to talk about before we do so is the importance of planning before you start writing code. This is incredibly important to think about before you ever start writing a single line of code. I would compare this to something like a building, where you just start building it from the ground up without having a plan. You probably wouldn't end up with the best building if you decide so without knowing not only what you want to create, but to plan everything before the buildings, and also think about what kind of materials we need to build our building. Well, it's really similar when we're writing code. We really need to take a step before we get excited and start writing things, and not only try to think about what exactly we want to create, but trying to think about the steps we might need to take and what we might need to achieve our goal. So with that, let's go ahead and take a look at our main.js file for this lesson, which just for record let's make sure we're working on the 11_begin folder, which once again you can just press Open Folder in Brackets. And then in our project files you'll just want to make sure we're in 11_begin and that you press to Select the Folder. From there we can double-click on any file we want to bring up here into our working file. So you can see I have our index.html file, our main.css file, and our main.js file. In our main.js file I created a little a project plan for the code we're going to write in this lesson. That way you can see how I might start to break down some of the steps that I want to do and how I might plan that out in order to get the result. So the first step I always like to do is to try to think about what I want to create. If you remember back in Volume 1, we created a Zombie Text Adventure Game as one one of the final projects. So now that we've learned all of the syntax we're going to learn in Volume 2, I'd like to revisit that same idea and try to think of new ways we might create our Zombie Text Adventure Game using the code we've learned throughout Volume 2. So for example, if I wanted to create another version of the Zombie Text Adventure Game, I might make it a little bit more complicated this time now that we have the syntax or the coding patterns that allow us to do so. So for example, I decided that for my Zombie Text Adventure Game I wanted to start out with a random scenario. I then wanted the player to search for a weapon and find a random weapon and then fight the zombie. This time the player has a 33% chance of getting bitten and losing or then killing the zombie and winning. So you can kind of see here that I started to think from the beginning of the game I wanted to create, maybe what I wanted to happen in the middle, and then what would happen in the ending, being as detailed as possible and even including what chance of winning I want the player to have. The next step I would do is to create the plan or the steps I think are necessary. So for example, for the beginning I might start by writing the scenarios I want, I would store a list of the possible scenarios, and then I would alert a random scenario from that list of possible scenarios. You can see I did the same thing for our weapon. So I created a list of weapons, I saved that list of weapons and then I want to alert which weapon the player finds. For the third step in the planning process I started to try to think about what I wanted to create and what kind of syntax or coding patterns I might use to achieve that effect. So for example, you could see we have a lot of lists here, so I might create arrays to store those lists. And I also have a lot of random scenarios happening; we have a random scenario, we find a random weapon. So I might also need to create something like a function to generate those multiple random numbers to reduce that repetition in the code. The last thing I want to note is that there are many ways to create things with code. So the most important part is to actually start writing it and worry less about what --- the fact that what you're writing is perfect or that it's very elegant, and just trying to make it work, trying to make it simple, and then building on the complexity and then figuring out where we might improve our code. So with that I want to go ahead and get started and show how I might start off this game here. So the first thing I want to achieve is to have some beginning scenarios from which to choose a random scenario to alert the user. So our first two steps here we can achieve in the same line of code. We can create a variable and store a list of possible scenarios as an array. So I'm going to use my var keyword and then I'm going to give my array a common sense name like, beginningScenarios. So I'm to type that in, just beginning --- whoops not three ns, scenarios and then we need our assignment operator, our single =, and then we use our straight brackets, which almost sounds like straight jacket, but not quite, and then we insert our scenarios inside. So I went ahead and wrote these out ahead of time just so you don't have to watch me type them out one by one. So you can see we have one, two, three different possible beginningScenarios, but you could add as many as you would like. I just started out with three; I think that's a good number there. So now that we have an array with three possible scenarios we need to alert what scenario that the user is going to see. So we're going to create an alert. And then we need inside of our parenthesis whatever we want to alert. So I'm going to add that semicolon so I don't forget it. And inside of here we're going to do something that is a little bit complicated, but if we think about this step by step it looks much more complicated than it actually is. So what I want to do here is we're going to pull out a scenario from our array. So I'm going to use that array name, which is beginningScenarios. So I'm going to press Enter so I don't have to type that out. And next we're going to be choosing a position in the array. So we're going to be choosing, if you remember our syntax for an array position is something like whatever the array name is, and then in our straight brackets we would just say 1, if we wanted our second position in the array if you remember, it starts at 0 or if we want the last one in this array we might be two. So it would be 0, 1, 2 or something like that. So following this syntax I can add my straight brackets and then I want to choose a random position and the array. So this is where I'm going to start to need my random number. So I'm going to go ahead and write my random number function. And we always want to create a function before we need to use it in the code or create a variable, or whatever piece of code we need before we're using it in our code. So I'm going to do it right after our beginning scenarios and before we need to use it in our alert. So I'm going to create a function called, randomNumber. And then we need our parenthesis, which is what --- where we'll be putting our parameter; and I'll come back to this in just a second. And then we need our curly brackets to add the code we want to Run every time we're using our randomNumber function. So inside of here we're going to be returning a Math.round. If you remember this from Volume 1, it's going to round our number inside of parenthesis. So whatever we put inside of here, it's going to round to a whole number. And we're going to ask JavaScript to generate a random number for us using the Math.random function. So if you remember that from Volume: 1, we just Math.random, and then our two parenthesis, and this the function that's going to return a random decimal between 0 and 1. So the next thing I want to do is --- this is always at this point going to round our random decimal between 0 and 1. So we're always going to get either 0 or 1. And I want my function to be more flexible than that and to be able when we call our function to specify a range. So every time we create our random decimal, we're going to multiply it by whatever range we specify when we're calling or using our function. So that's what I'm going to include as the parameter for my randomNumber function. So I'm going to type in range here. So every time we call a randomNumber, let's say I put in 4 as the range it's going to create a range of decimal and it's going to multiply it by 4, and then round the result. So we'll either get 0, 1, 2, 3, or 4, if we were to include 4 as our range. So now that we have a range of number function, we can come back to our alert, and we're going to call a random scenario in our array. So as the array position rather than specifying something like 1, or 2, or 3, which will always return the same scenario, we're instead going to use a randomNumber that will be a position in the array. So I'm going to use that randomNumber function, (Typing) if I can type that correctly, and inside of the parenthesis here we're going to pass it our argument. So it's looking for a range, and I want our range to be whatever the length of our array is. So I'm going to write this out and then I'll go ahead and explain it right after this. So I'm going to type in the name of our array, which is beginningScenarios. And if you remember we have an array .length property, which is always going to return the length of an array. So we can add as many scenarios as we want to this, and it'll calculate that for us. And this always returns one number greater than the position in our array. So since this starts at 0, we have to offset the fact that it doesn't start at 0 --- or I mean it doesn't start at 1, it starts at 0. So we're going to say our array .length - 1. And I know that is kind of complicated and confusing, but if you kind of start to think about it step by step hopefully it will make a little bit more sense. So what this is going to do is it's going to alert and it's going to look in our array. It's going to generate a random number that has a range that's whatever the length of array is - 1. So that'll mean that it will return either 0, 1, or 2, and then pass that position to our scenario. So I'm going to go ahead and delete this little syntax I wrote here. So let's go ahead and test it at this point. So I'm going to go ahead and Save this, and it's going to Run. And you can see we're getting undefined. So obviously, we've done something a little bit wrong here. So we can come in here and take a look. And let's see here, I'm going to go ahead and Refresh it again. And we're getting undefined every time. So this is just a little troubleshooting exercise so we can see how this would happen if we were getting undefined. So I'm just going to scan through here in my code, and see what might be causing that area. And I can see actually in our randomNumber function that I've forgotten to add a keyword. So right now we're generating a random number in our function, but we haven't told our code what to do with it. So we could store it in a variable or we could also use the return keyword, which is going to tell our function to return a value. So I'm going to use that keyword there, return, and now if I Save this then we should be able to see our code working. So I'm going to hit Control + S, and now yeah, you can see that we're getting a random scenario from our array. So if I Refresh our page we should get a different one. So you can see as we're testing this now, we're getting a different --- a different scenario from our beginning array every time we Run our code. So very very cool. For the next thing in my list you can see we have our beginning scenario working. And I might go ahead and Create a list of our weapons, Save the list of weapons, and Alert which weapon the player finds. So I'm going to go through this a little bit more quickly since it would take a long time for me to go through everything. So the first thing I would want to do is I would create an array, and I'm going to call it weaponList. And in that array I'm going to store whatever weapons that I want to have in my game. So maybe I want one option to be a "shovel", then I might have something like a "crossbow", (Typing) maybe a "baseball bat", (Typing) and then just for fun we'll through back in our fancy "rubber chicken" from Volume 1. And then we just need to finish with our semicolon. And then just like with our beginningScenarios, we're going to do something very similar in order to return a random weapon. So I'm going to go ahead and Copy and Paste this and then we'll go through it just to save some time. So I'm going to Paste this in here. So I have our weaponList, and then I also created a variable called weapon. And it's storing a random weapon from our weaponList. So this is the exact same syntax from our beginningScenario. So we're using our weaponList array and returning a random number that is always going to be a position in this array. So it's always going to be either 0, 1, 2, or 3. Next, we're going to alert a little scenario about finding a weapon and show the message about what weapon we found. So I'm going to hit Control + S to Save. We get our beginningScneario and then we get our little message, and now we're finding a random weapon. So we can press OK. So we could go back here to our plan. We have our beginning, we have our weapon, and the last step is to fight the zombie and have a chance of getting bitten and losing or killing the zombie and winning. So just like we just did I'm going to go ahead and Copy and Paste this and then we'll go through it just to save all of that typing. So I'm going to Paste this in here. And after our weapon here we have another alert. So I just created an alert since this is going to be running from top to bottom. And it's going to say, "Suddenly a zombie bursts through the door!" We ready whatever weapon we had. Remember we stored it in a variable, so now we can use whatever weapon that was randomly selected from this list anywhere throughout our code. So alert that we "ready our weapon and advance towards the zombie." And then I created another variable called, survival. It's going to calculate whether or player survives or dies. And that's going to be a random number; that's going to be 0, 1, or 2, which if you remember up here, there's going to be a 33% chance of getting bitten. So if survival is = 0, so if our random number is 0 the zombie's going to bite you. So if we have three numbers: 0, 1, 2, or any number in that list really, will be a 33% chance, because you have a one in three change that that number's going to be selected. Otherwise, so else if survival is > 0, so if our randomNumber is > 0 then we're going to kill our zombie with our weapon and we win. So I'm going to hit Control + S to Save this. And we can go ahead and take a look at our game. So we have our randomBeginning scenario. We have our message about finding a weapon. So now we find our "rubber chicken". And we can press OK. The zombie bursts through the door. We're going to fight him with our rubber chicken. And we killed the zombie, and we win. So while this is a relatively simple game you can that we have a lot of different logic here that's come together to create our game. And while this seems kind of complicated or a lot at first, I didn't write this in just two or three minutes, I came back here to my plan and really tried to logically think through each piece and figure out the best way possible to achieve what I wanted to achieve. So the last note here is if you're having trouble achieving what you want to do, so maybe I'm having trouble creating a random scenario, there's nothing wrong with scaling back and maybe having the same scenario beginning every time or something like that. The most important thing is to write it, get it working, and if you can't get it to work, make it simpler and then come back after you have it working and figure out ways to make it more complex or more interesting and also how to improve our code. So now that we've taken a look at the planning process and how we could create a more complicated version of the game we created in our first volume, in our next lesson we're going to get our volume to assignment and create a plan.
Volume 2 Assignment
In this lesson we'll get our Volume 2 assignment. For this lesson we're working out of the 12_begin folder, and I also have the main.js file open. For your Volume 2 assignment I'd like you to build on the complexity of the game we created in Volume 1. For reference I've included the code we created in Volume 1 below. And the reason we're starting here and not from the code we created in our last lesson, is that the code we created in our last lesson is much more complicated and it's going to be more difficult to build on the complexity of that. So if you do want to work on what we created in our last lesson instead, I've included it in a file called zombie.js. If you wish to work on this file instead then all you need to do is come into our index.html file and change the file path of our main.js file to match the zombie.js file instead. So taking a look at this, what I did in the last lesson is I took the game we built in Volume 1 and I tried to start to go through and think of ways to improve it. So for example, you can see that we start by alerting the same beginningScenario each time. So I decided that it might make it a little bit more exciting to have a random scenario instead and I added that to my plan. From there we have the option to choose a weapon. So we could keep it that way, but I thought it would be fun to leave that up to chance and have the player fight with a random weapon instead. So using that kind of thinking pattern I'd like you to take this code and build on it in your own way. So a couple of ideas to get you started are maybe creating a randomNumber function that generates a random number within a certain range. And then you can find a way to include more randomness in your game. So for example, maybe you want to create your own list of weapons or maybe you want to have your own custom ending scenario, or something like that. A second idea is to generate a random scenario for the beginning, just like we did in our last lesson, or maybe the ending. And if you don't know how to do that or maybe how you might do it differently, since we can do code in many different ways, you might try by using a switch statement that takes a random number as a parameter and alerts a scenario for each case depending on which random number we have. So that's another idea. Or if you don't like zombies, or you want to have fun creating your own adventure game, maybe take this code and using some of the ideas from it create your own Text Adventure Game. Or if you find this version right here that we created in our last lesson to be more exciting, feel free to just go in here and change the existing code and build on it or create your own game using this code and maybe thinking about how you might do things a little bit differently or repurpose them for the context of your game. I don't expect you to be able to write something like this right away because it takes a lot of practice to be able to write code from scratch. So if you're struggling with that as you're doing this exercise and your having a hard time thinking about how you would write code of your own, I really recommend you just come in here and do this. Maybe just change the beginning scenarios, the weapons, things like that to create something of your own. So with that, good luck and I can't wait to see what you create in your Volume 2 project and I'll see you around for Volume 3. Thanks for sticking around and I hope you've enjoyed quick start to JavaScript Volume 2.
Course author
Susan Simkins
Susan is a web design author for Pluralsight. Growing up, Susan was both a passionate artist as well as a computer tech aficionado. When she discovered the world of web development, she found that...
Course info
LevelBeginner
Rating
(748)
My rating
Duration1h 53m
Released4 Dec 2014
Share course