What do you want to learn?
Leverged
jhuang@tampa.cgsinc.com
Skip to main content
Pluralsight uses cookies.Learn more about your privacy
Code School: JavaScript Road Trip Part 2
by Jason Millhouse
A continued introduction to the very basics of the JavaScript language after the Code School: JavaScript Road Trip Part 1 course.
Start CourseBookmarkAdd to Channel
Table of contents
Description
Transcript
Exercise files
Discussion
Recommended
The Labyrinth of Loops
While Loops
Hey everyone, and welcome back to the Road Trip JavaScript Two. If you complete the first course, you now have an elementary education in the basic elements of the JavaScript language. In this course we'll be exploring more of those fundamental concepts that will build the skills you need for your future in web development. So, all aboard, come back and join us on this the second course of the JavaScript Road Trip. From the labyrinth of loops To the variable valley We'll see the cliffs of value first JavaScript's right up your alley Built ins, bluff, files falls Or ray archipelago Declarations in a desert where you'll find out How far you'll go Learn the program, take a ride Buy a ticket, step inside All aboard are at the station to increase your education Bon voyage and skinny dip As long as functions you don't skip On this the JavaScript Roadtrip Hey road trippers, here comes level one of the Labyrinth of loops. Don't get lost. Don't get lost. Don't get lost. Don't get lost. So, in our last level we had some pretty repetitive code that kind of sucked a lot and we want to try to improve that situation. A loop is going to allow us to do that. The first loop that we'll look at today is a while-loop and the while-loop will run its code just so long as its Boolean condition evaluates to true. Here we have a basic while loop setup that includes the while loop keyword and then a set of parentheses. Inside this parentheses is going to be an expression and if that expression evaluates to true, the content of the loop, the code inside the loop will execute. Then it will go back to the top of the loop and check the expression again. If the expression is still true, the code inside the loop will be executed again and this will continue until the condition inside the parentheses is false. Now, what does this mean? It means that if we had a while loop where we explicitly wrote true as the condition that means that while loop would go on forever and forever ad infinitum and would never stop, it's called the infinite loop. Additionally, if we had false hard coded into the while loop that while loop would never run at all. So, we're good with the true and the false conditionals inside a while loop, so now let's make a loop that prints the numbers one through five in ascending order. We need to think about this a little bit to make sure that we get the exact right output. The first thing that we'll need to do is establish a variable, let's call it number, and we will set that number equal to one since that's our starting point. Now we'll build the while loop. So, here you can see inside the while loop that as long as our number is less than or equal to five, we will print the number with a console.log and then we will increase our number's value. It's important that we increment the number inside the loop because it's going to advance our number through the numbers that we want to print but it's also going to eventually become greater than five and therefore stop the loop. Now, if we were to run this code, the loop would execute five times and within each loop, a number would get printed and then incremented. So, now the important thing to understand about loops is that they will allow us to execute code repeatedly without typing forever which is really terrible. So, what we want to do is try to apply this to our trains situation what we want it to print a message about which trains were running. Here we want to execute the following code for every one of the running trains. Now, that bracketed word number is just a placeholder for the number value of the train that we want to print. Now we know our variables can be changed, so let's make one that will count our trains in the loop that we're going to produce for this code. We're going to set it to one because obviously the first train that we print will be one. Then we need a way to make our train counter increase on every repetition. Obviously that will go with our incrementation code. TrainNumber++. When we put those code items together we can see that the following code will need to loop back until all running trains have been listed and we could also say that this code needs to run as long as the trainNumber is less than or equal to eight because there are eight running trains today. Let's trace through the loop we actually need. First, we'll initialize our trainNumber value to one. This will both help control the loop and be used in our printouts. From there the loop will only continue if the trainNumber is less than or equal to eight. Then our loop will actually execute its contents and what are those? Well, they're printing out our running train message using the trainNumber variable inside our console.log method. Once that code is finished we'll perform the very important step of incrementing our trainNumber which steps forward to the next train and will eventually stop our loop. After incrementing our variable with trainNumber++ we'll cycle back up to check the less than or equal condition again, this looping procedure will continue until the trainNumber is greater than eight and the loop should stop. Now, the while loops for this is going to look something like this. In there you can see our initialization of the trainNumber one, you can see our condition to check which is is the trainNumber less than or equal to eight? You can see our printout of the train message and you can see our incrementation of the trainNumber. Let's take a closer look at the values that happen when we run the loop. The very first thing the trainNumber gets set to is the value one. Is the trainNumber less than or equal to eight? Yes, it is so that condition will be true and so the loop output will be train number one is running. After that gets printed, trainNumber gets incremented to two and the same procedure occurs all the way through the loop printing out new train numbers until the trainNumber is nine. As soon as that happens, trainNumber is no longer less than or equal to eight and so, that condition is false and the loop will stop. Let's migrate our while loop over to the trains.js file. Now, in our trains.js file we want to use variables instead of hard-coded values to control our train loop. Why would we want to do that? Because not every day will there be eight operational trains. Some days we'll have operational trains of 10, so we want to be able to make our loop respond to the contents of a variable and not to a hard-coded value. So, here we can see that we have our trainsOperational variable set to eight today and our train number variable of course will start at one. Here's our while loop and notice that inside our conditional now we check to see if the trainNumber is less than or equal to the trainsOperational variable. That will ensure that on any given day as long as the trainsOperational variable is set to the correct amount of running trains, we'll get the exactly correct loop of printout.
More Loops
Now we'll move on to a different style of loop but one that has similar functionality. It's called the for loop. It's a different way of producing nearly the same looping behavior. Here you can see the basic outline of a for loop. It starts with the for keyword and then has a relatively long set of parentheses. Inside that parentheses you can see two semicolons that break up three separate statements that will go in the for loop's parameters. In the first expression we typically initialize our variable counter there. The second expression is typically the condition we check to see if the loop will continue. And the final statement inside the for loop's parameters is the thing that we want to do code wise after each loop. Usually this is an increment or decrement statement to control the loop. Of course inside the loop is the code that we want to be repeated over and over. So, now if we think back to our train while loop we can demonstrate the same exact functionality with the for loop. Let's see how we do that. In our starting expression we would have the variable trainNumber assigned to the value one. Remember that was the statement that we executed on the outside of our while loop. Again, the second statement is just going to be that same condition that we checked for the while loop to see if the trainNumber is actually less than or equal to the train's operational variable and the third statement will increment our trainNumber every time our loop executes. Now let's take a look at how this for loop actually proceeds through the code to sort of get a visualization for the flow of the for loop. In the first statement the trainNumber variable will be initialized to one. After that happens that particular code will never be run again. Once that first statement is executed it is finished and over. It will move on to check the condition in the second statement. We will see if the train number is actually less than or equal to trainsOperational. If it is, we will go ahead and execute the loop's code, all of the code contained within the loop will be executed. Once that code is finished, we will come back to the third statement in the parameters and here we would increment the trainNumber variable so we can move onto the next train and also get ready to stop our loop eventually. From there we go back to the second statement and see if the trainNumber variable is still less than or equal to trainsOperational. If it is, we continue the loop again and the cycle continues until when? The trainNumber variable is greater than trainsOperational. We used a while loop to print the numbers from one to five in ascending order so now we're going to use the for loop to print those numbers in descending order. Let's take a look at how we might do that. So, the first thing we do in our for loop is we initialize the number variable to five, that's going to be our counter variable. Then we only want to run the loop as long as that number is greater than zero and at the end of the loop we want to decrease that number's value by one. Inside the loop we will log the number out to the console. Let's take a look at this code's execution. When the value of number is five, well, clearly five is greater than zero, so that condition would evaluate to true and then we would get a printout of the number five for that particular loop. That cycle would continue until number reached a value of zero and when number was zero it would clearly not be bigger than zero and so, the condition would be false and the loop would stop. Great, so we know while loops and we know for loops, so now let's see if we can identify the non-operational trains. So, we've already identified the operational trains, now we're going to identify the ones that are not running for the user and this time we're going to use a for loop. So, let's see, which trains are not running? Well, we know we have eight operational trains today, so probably the very first train will be nine that's not running but we have to think about how to put that into the for loop a little bit creatively. So, we know we have eight operational trains and 12 total trains. So, let's start our for loop by creating a variable called stoppedTrain. And we don't want to hard code this value, we want to make sure that we use a variable to signal which of the stopped trains it should be. Here we know that the very first stopped train will be the one immediately following the last operational train. So, therefore if we just added one to the trainsOperational variable, we will have the train number for the first stopped train. Then for our condition, we want to make sure that our stoppedTrains list never goes past the total amount of trains. This is the first time we've used that totalTrains variable in a loop and then at the end of a loop we should of course increase our stoppedTrain number so that we can get all of the right stopped trains printed and then stop the loop. Inside the loop we'll of course print out a message to the user that this particular train is not running. If we were to execute that code, we would get the following four statements today. Wahoo, stopped trains only. Okay, now we have a list of running trains with our while loop, cool and we also have a list of our not running trains with our for loop and we're going to add both of those now to our trains.js file. If you take a look here you can see we've established both the totalTrains and the trainsOperational variable in our trains.js file. Then we have our while loop that we built before. This will print all of the running trains. To that we're going to add at the end our for loop that then prints the stopped trains. What will this look like if we run our current solution? Well, the first thing that will happen is it will execute the while loop and it will proceed in the exact same fashion that our previous while loop preceded. It will cycle all the way through train number eight printing that each one of those trains is running and then when it arrives at train number equals nine, we will get a false value in the loop's condition and the loop will stop. Then it will proceed to the for loop. Now we can see our entire solution running with two loops where we get all of the running trains printed and then all of the stopped trains printed. Wahoo.
Conditional Canyon
Loop Slide
From the Labyrinth of Loops To the Variable Valley We'll see the Cliffs of Value first JavaScript's right up your alley Builtin's Bluff, Files Falls, Array Archipelago Declarations in a desert Where you'll find out how far you'll go Learn to program, take a ride Buy a ticket, step inside All aboard, you're at the station To increase your education Bon voyage and skinny dip As long as functions you don't skip On this the JavaScript Roadtrip (playful music) So now you're a master of the loop, right? Hope you enjoyed level one and now on to level two. Sometimes when we're developing, our code needs to decide whether to take one track or the other and so we have arrived at level two, Conditional Canyon. (train horn) You'll remember in the previous level that we printed out all operational trains as well as all nonoperational trains in our new train system. We used two loops to do that and here is our previous code. You can see that we used both a while loop and a for loop to get through all of the trains. Our goal here is now to get all of that code inside one for loop. How would we design that? Well here we have a for loop that loops through not just the operational trains but through all of the trains. We have it checking to see whether the train number is less than or equal to the total amount of trains. That means that this for loop will move over every single possible train number. But now we need to know how to differentiate between whether the train is running or whether it's not running. So if the train is currently running, we want to print this particular statement and if it's not, we want to print this other statement that show that it's not operational. How can we do that? Again, the goal here is to figure out how we can run different lines of code based on different conditions. Guess what, we have a JavaScript trick for that and it's called if and her buddy else. The if and else statements allow us to execute certain code but based on specific conditions. Here is the basic shell of an if and else statement. If some condition is true, then we're going to do this code. This code is the code inside the if block. Else says otherwise do this code instead. Notice that if a condition in the if block is true, only the if code gets executed and the else code only gets executed if the if condition is false. Here's a basic example of conditional execution. Say we had two values, value one and value two and we've set them to four and nine. Let's use some conditional statements to compare and print out whether one is greater than the other. Here we can see that if we do a comparison of if the value one is less than the value two, we print out that that is true, value one is less than value two, else, or otherwise, meaning if value one is not less than value two, we would print out that value one must be greater than or equal to value two. That's because we don't strictly know whether value one is greater than because it might be equal to. So in this case because value one is four and value two is nine, the if block would trigger because it's conditional would be triggered. Value one is less than value nine and so we would get the print out that four is less than nine. What happens if we change value one to 12? Obviously we have a different relationship now. So now the if block will not trigger. Why, because 12 is not less than nine and so we will move into the else block and we will get a print out that says 12 is greater than or equal to nine, just trust us. Now that we've got some experience with an if and an else block, let's go see if we can make a difference in our problem. Our original problem was that we needed to figure out whether a train was running or whether it wasn't inside one loop and now you can probably see how we would use an if and an else to make that situation work out. So we know that if the train number is less than or equal to the operational trains, that means that it's a running train because we know that all operational trains are numbered from one moving forward. Therefore, we can print out that that particular train number is operating. Next we know that if trainNumber was not less than or equal to the operational trains, it must be greater than the operational trains and therefore a non-running train. So we would print out that it was not operational. So now let's run our new single loop with our special conditionals. We can see that when trainNumber is one, the first thing that happens inside the loop is it checks the loop condition. Is one less than or equal to 12? Yes, it is, that's true. So we will move forward with the loop, the loop will actually continue. And then it will check the condition. Is the train number one less than or equal to eight? Yes, it is, and so we will move into the if block and print out that train number one is running. That same procedure will happen all the way through train number eight where we'll get printouts that each one of those trains is running. When we finally get to the trainNumber nine, what will happen is the loop condition will check out, it will be cool and we will continue the loop but our train number nine is not less than or equal to eight and so we will move to the else block instead of the if block and now we will see that train number nine is not operational. That same procedure will occur through the remaining trains all the way to train number 12. That will be our last non operational train but when the train number becomes 13, finally the loop condition itself will be false and the entire loop will stop. So now we have printed out every last train and whether it is running or whether it is not and we have done it all in one magical loop using conditions.
A Loopy Problem
(upbeat music) Now we'll throw a special case into the scenario. What if we had a train, a special train, an express train, that starts later? Let's add a train that isn't one of the regular running trains but it also is not a non operational train because it will start at noon, it's a special train. To do this in our code we will need the else if syntax, that's for when two conditions just is not enough. So let's take a look at that. We already know our if block, where if some condition is true, we're going to do some code and the else if comes in when we need an extra condition to check before we fall to the final else block. You can see that in the else if block if some other condition is true, we will do the code inside that particular block before we will allow the code to proceed down to the else block. Something to remember is that if any condition is ever met inside the if block or in the else if block, the else will never get evaluated. Else if allows us to check multiple conditions. It can be used when many specific scenarios need attention. So let's take a look at how we might apply the else if block to our special train situation. Here we have our normal if the train number is less than or equal to the operational trains, let's just go ahead and print that that train is running but now we need to check something specific, otherwise first check if the train is the express train then we want to print that train number 10 begins running at noon because it has its own special message. Otherwise we know it is neither a running train nor an express train and so it is a not operational train. How can we implement that particular part of the else if statement? Well all we have to do is ask whether the train number is exactly equal to 10, if it is, we know it's train 10, and we can print out that that particular train is running at noon. Something to note is that the else if condition is never evaluated at all, if the very first condition in the if block is checked and is satisfied. Similarly the else block will only trigger when the above two blocks have failed. So now let's update our system status loop with our cool new else if statement. We can print based on multiple conditions now. So you can see that in our for loop, most of which you've seen before, we've added in the else if statement to check to see whether we have train number 10 and then print out that it runs at noon. So let's go through the execution board again and see exactly when that else if block is triggered. You can see that for the first eight trains that else if is completely ignored because the if block is triggered. And then on train number nine, since nine is not equal to train number 10, we go straight to the else block and print the ninth train is not operational. On the 10th train, finally we have triggered our else if block and we see the printout that train number 10 begins running at noon and then the rest of the trains proceed as normal and the loop stops at train 13. Sometimes when we check a condition, we need to check another condition inside that block before we continue with the code. A nested conditional will help us do that. Let's say we had some shapes. We've got two sizes for squares and we got one size for circles. We want to color big squares red and small squares blue and since there's only one size circle, we'll color that purple. How can we do that in pseudo code, how can we make the decision as to whether a shape should be colored red, blue, or purple? Well we know that if it's a square, we should check whether it is big. If it is big, we want to make that square red. Now if it is not big, we will move straight into the else block, which means it must be a small square and so we should make it blue. Now this extra else here on the bottom is going to take care of our circle. Why, because we know that if our shape is not a square, it must be a circle and so, therefore, we're going to make that purple. This is an example of nested conditionals. Something to note here is that the innermost else block only responds to the innermost if block. Additionally, the very last else block only responds to that first if conditional that checks whether the shape is a square. Say that in our train system, we wanted to print out a special message to our users that said whether all trains were running or none of them are. We can use nested conditionals to check whether we have all trains running or none. How can we demonstrate that kind of situation in pseudo code, let's take a look. So if there are any running trains, meaning any running trains at all, the first thing we want to do is check to see if the amount of running trains is the amount of total trains and then we want to print out to the passengers that all trains are running if that is true. Otherwise, we'll just execute our normal loop code to decide whether we have a running train or a not running train or a special train and then outside all of that nested conditional, we'll have that final else block that says there must be no running trains, and so we will print that out. How do we know that? Well if the very first if statement fails, that means there's no running trains and so we can go straight to the else block and print out that there are no running trains. So let's check out how we would make some code out of that situation. Well in our first if conditional we would say if if the train's operational is greater than zero, that means we have some running trains today, if that's true then the first thing we need to check is whether the trainsOperational, meaning the amount of running trains, is equal to the totalTrains. If that's true then, of course, we know that all of the trains are running and so we can print that out to the user. Otherwise, then we run our basic for loop that we have already designed to differentiate between the running trains, the not running trains, and our special train. And then on the very last else block, we will know that there are no operational trains and so we can print to the user that no trains are operational today, bummer. So now if we update our train.js file with our special new nested conditionals, our passengers will know whether all of the trains are running today or whether none are or whether it's a mix of the two. Something to note here is that all of our code is very efficient because it's controlled by just two variables. Let's see what would happen as we trace through our crazy nested conditional code. Let's see how we'd get these particular situations where we'd have all trains running or none. Well first, we know that we have 12 total trains, right, and we also have in this particular case, 12 operational trains, hmmm, they equal each other. Well we know that the trainsOperational variable is greater than zero, so we will move into the very first if block and then we will check to see if the trainsOperational variable is the exact same as the totalTrains variable. In this case it is and so we will instantly print out that all trains are running at the JavaScript Express, woo-hoo. Now what would happen if we set our trainsOperational variable to zero, that means we have no running trains today. It must be a holiday. So now we'll come down and we'll say is trainsOperational greater than zero? It is not and so we will move straight to printing no trains are operational today, bummer, in the final else block.
Loop Echo
(upbeat music) So now let's see if we can add to our complex list of special trains. We want to make train number 12 become a special train just like number 10, they bother begin running at noon but how can we do that? We want to make sure that we only handle that particular special case with one conditional. Let's look at how we can do that. So in our original loop where we checked each train number to see what we should print for that train number, we're going to need something a little extra in the else if condition to see whether we've got train 10 or train 12. Also, we need to change the console.log statement because we don't want to print that train number 10 is running when it's actually train number 12. So we'll concatenate a train number variable inside there to handle that. The special syntax that we have to evaluate two conditions at once is called a complex conditional and we have the binary and, which is two ampersand symbols in a row, and that's going to return true if both values on the left hand and right hand side of the ampersands are true and we also have the binary or, which returns true if either value on the left hand or right hand side is true. If we had a situation true and false, that's going to evaluate to false because not both of the value are true. If we had a situation where both values were true, then that's going to turn out to be true. If we also had a situation where both the values were false, well we don't have any truth value there, so that's going to be false too. Moving onto or, if we saw a situation where the left hand side was false and the right hand side was true, well all we need is one truth value to make that or return a true and so this will return true. Next we have a false or false, you see that situation, well, we don't have any truth value so that will give us a false back. Similarly, if we had a true or a true, we've got more than even truth value to make that or work out and so we have a true. Let's take a look at how these might be evaluated with expressions. Here you can see that 11 is greater than or equal to 11, that's true, and negative seven is less than six, that's also true. Since we have two expressions that evaluate to true, that entire truth value expression returns a true. Over here if we have two greater than or equal to zero, that is true, but then nine is not less than four and so that returns false and this entire complex conditional will return false. Next we have is five less than seven? Yes, it is, is eight greater than 10? No, it is not and so we have a true or false situation but that's okay because or only need one truth value to return a true. And then lastly, we can see is three greater than eight? No, it is not, so it is a false situation and is seven less than three, no it's not, it's false and so a false or a false will return a false because need at least one truth value to return a true. Now let's see how we can use that inside our trains.js system. Let's think about how we can add a complex conditional to our else if statement to make sure that both train 10 and train 12 get printed correctly as express trains starting at noon. So what we would want there is to check whether the train number is 10 or whether the train number is 12. If it is either train number 10 or train number 12, then we will print out that that particular train number will being running at noon. Let's take a look at our new status loop. We can see that as normal all of the operational trains will run, one through eight, and then we hit train nine and we see that that's not operational and then at train 10, we trigger the else if to show that train number 10 begins running at noon. At train 11, we see that that's just a regular not operational train and train number 12 will now trigger our else if block with our complex conditional and we see that it begins running at noon. Guess what, we're going to continue now adding to our list of special trains, oh no, but it's going to be a different special train this time. It's going to be train number three and we're going to say that train number three only runs on Sunday, so it is not a regular train, it is not an express a train, it is not a non operational train, it is only a Sunday running train. We're going to use our binary and complex conditional syntax to manage this situation. We want to make sure that train number three runs only on Sunday, so we will need a day of the week variable and we're going to initialize today to be Friday. We know that if today is Friday, then train number three should not be running. So let's see about making some code that makes that happen. So here's our regular status for loop that checks the train number to see what should happen in the printout. What we need to do here is add an extra else if condition that checks two things, whether the train number is three and if the day is Sunday, if that's the case, then we can print that train number three is running. How can we show that with our complex conditional syntax? We can ask whether the train number is equal to three and the day of the week is Sunday. If the left hand side of that and and the right hand side of that and both evaluate to true, then we will get a printout that says train number three is running. We can go ahead and hard code that three in the string because we know that train number three is the only Sunday running train. So let's run this code and see what happens. We should get that the train number three is not-- Oh no, the train number three running. What happened, something's wrong with our code. Why didn't we get the right status? Let's trace our loop logic and see exactly what the problem is. So if our day of the week is Friday and we know that we have 12 total trains and eight operational trains, we know that at some point in our status loop the train number will become three. If that's the case, then when we go to track that the train number is less than or equal to the operational trains, we will get a true, which means that we will go ahead and print that train number three is running, without ever having checked whether it's Sunday. But we know that it shouldn't be running because it's Friday so we have to make a shift in some part of our code. How can we do that? Well we found our logic bug and it's in that check of trainNumber less than or equal to operationalTrains that's because for train numbers one through eight, they will always trigger that very first if block and we will never reach the else if block that checks if today happens to be Sunday. How can we fix that? We can put an extra condition inside the very first if statement that says if the train number is less than or equal to the operational trains and the train number is not three, now how can we get some syntax that says the train number is not three? Well that's very simple, you've seen that before, we would just have double and trainNumber not equals three and that will also ensure that when we get to the train number three, we will fall all the way down to the second else if, check both that the train number is equal to three and that the day of the week is Sunday, then print that the train number three is running. Now we'll get correct printouts with this particular syntax. We can see that when the day of the week is Friday, we now get the correct printout that train number three is not operational and when we set the day of the week finally to that glorious day of Sunday, we get that the train number three is running after all. So let's look at how this complex conditional arrives at the different unique printouts for train number three. Well let's say our day of the week's Friday. We'll look at the Friday condition. We know that at some point, our status loop will arrive at train number three and when that happens, it's going to then check to see if the train number is less than or equal to the operationalTrains, which it is, and then it will also track to see that trainNumber is not equal to three, that will be false, and it will make sure that we do not enter that if clause and then we will check to see whether the trainNumber is 10 or whether it's 12 and since it is neither, that entire condition will be false and then we will check to see if the trainNumber is equal to three, which it is, and then we will check to see if the day of the week is Sunday. In this case, it is not, and so we will get that train number three is not operational. Now what happens when the day of the week is Sunday? We get nearly the same situation all the way through except when we check whether the trainNumber is three and whether the day of the week is Sunday and since both of those situations are true, we finally get that train number three is running.
Built-in's Bluff
Built-in's Bluff
From the labyrinth of loops To the variable valley We'll see the cliffs of value first JavaScript's right up your alley Built ins, bluff files, files Or ray archipelago Declarations in a desert where you'll find out How far you'll go Learn the program, take a ride Buy a ticket, step inside All aboard are at the station to increase your education Bon voyage and skinny dip As long as functions you don't skip On this the JavaScript Roadtrip So that was level two, conditionals are pretty cool huh? And another cool thing about the JavaScript language is that it has tons of built-in functions that you can use at any time. You can call them wherever you want and we're going to look at a few of those in this level three built-ins bluff. Let's take a look at some existing JavaScript functions that you can use to get and send information from the user of your website. The first one we'll take a look at is alert. This will send a message to the user of your website in a small popup window. You can see here that when we call the alert function we've placed a string inside of a set of parentheses that will get alerted to the user but you can put any expression inside these parentheses that will be evaluated and then presented to the user. Once the alert function is evaluated, a small popup window is present in the browser that the user can click OK on acknowledging that they have seen the alert. Another built-in function is the confirm function. It asks users for a consent to move forward with a specific action. Here we're using the confirm function to make sure that a passenger wants to ride train number eight. A small window appears when the confirm function is evaluated presenting the user with the opportunity to say OK or cancel. If the user actually hits OK, the confirm function is going to return a true Boolean value. If they hit Cancel, we'll get a false Boolean value. Yet another built-in function is called the prompt function. This will send a message to the user and also retrieve an entry. So, here we got a prompt function that says what soul hath allowed the canines to exit? And the user appropriately responds woof, woof, woof, woof and then hits OK to say yes, that is acceptable. Prompt is a cool function because you can request information from the user and then store it in a variable. Here you can see a prompt function that requests the user's name and that name gets stored inside the variable userName. When we run this code, a small window will pop up in the internet browser and the user can enter their name in the field that's inside the window. So, if Code School professor Gregg Pollack was sitting at our website, and entered his name into our prompt window, his name would get stored in the userName variable. We could then call that variable and his name would be returned. Now let's see how the confirm and the prompt methods can work together to ensure we have correct information from the user. If we prompted yo passenger, what's your name? And Gregg enters his name and selects OK, his name will be stored in the userName variable and then we can use the userName variable inside of a confirm function to ensure that he has entered his name correctly. A small window will pop up in the internet browser and ask Gregg if he's sure that that's his name and he can say OK for yes or Cancel for no. But wait a minute, what happens if Gregg presses Cancel on either the prompt or the confirm? We need a way of verifying whether he has actually inputted something for his name and then whether his name is correct or not in the confirm box. To do that we'll need the type of operator. The type of operator allows us to identify the kind or type of course of value inside a variable or an expression. Here you can see that if we take the typeof true as an entry we get Boolean as a response because true is a Boolean value. If we do typeof that's not a valid entry, we get a string because the expression that follows typeof is a string. Typeof 42 will return number and typeof undefined will return the type undefined which is its own type. And typeof null which is special and we'll need it soon returns an object as a type. The typeof operator is useful in checking a variable's contents, very useful here. You can see that if we prompted yo passenger, what's your name? And we stored that in the variable userName, now if the user ever selects Cancel regardless of whether they've input anything into the field, prompt will return a special value called null and null is not a string, so now if we were to take the typeof of userName which had a value of null, we would get a return from the typeof of object. That's because null is a generic JavaScript object. This is really cool and useful because then we can alert the user that they have not entered a valid entry. We can do that by saying if the typeof the userName variable is not a string, uh-oh, oops, you didn't enter your name and then we can start that cycle over to make sure that they have entered something acceptable. Now that we know how to handle a cancel from a prompt function let's look at how to handle a cancel from a confirm function. It's pretty easy because the confirm function returns a false value if we get a cancel from the user at any time. Then we can just use a simple if statement, a Boolean check to make sure that the user has confirmed their entry. If in fact we get a truth value from confirm, then we can do some code. All right, so now that we're masters of confirm, prompt and alert and know how to move between the three let's see if we can make a simple name entry system for our train service. We're going to write a confirmation loop and let's prepare some pseudo-code first that sort of plans our solution using these functions. So, in our trains.js file you see these three dots here? That just means we've got a whole bunch of extra code handling our trains. In here we will start our confirmation loop. We know that we want the loop to continue until the user has confirmed a name and inside the loop the first thing that we'll do is we'll request the name using our prompt function that we know, following that if the user says OK at a confirm function, we will acknowledge their accepted entry and then exit the loop because we're done and we don't need to check it anymore. Otherwise we'll cycle back to the top of the loop and start the service over. Okay, now let's fill this in with some real code. The first thing we'll need is a variable. We'll call it gotName that will tell us whether we actually have the user's name correct or not and we will use that in our loop. You can see here that we have a while loop that says while our gotName is false, that means we don't have the name yet we'll do the following things. The first thing is that we'll establish a userName variable just like we did before and then prompt to the passenger. Yo passenger, what's your name? And here's our cool if statement that says if we get a confirmation with the statement are you sure your name is and then the userName variable. If that returns a truth value then we'll alert to the user sup userName and then here's the money, we have to set the gotName variable which is a flag to true. So, now the loop knows that we have the user's name. Once that's true, what happens? We go back to the top of the while loop and we see now that gotName is no longer false and we would exit the loop because we have the user's name. But what would happen if the if statement didn't trigger because we did not get a confirmation? Well, we would cycle back to the top of the loop and continue the process again. So, now let's see this loop in action. Up here we have our index.html file as well as our trains.js source file within which is this code down here, our very basic confirmation loop that we just built. When we load our index.html file our loop in trains.js starts to load and we get our very first prompt and it says yo passenger, what's your name? That's this part right here inside our loop and we're going to go ahead and type in a wrong name, JohnnyAppleseed and select OK. Our loop says are you sure your name is JohnnyAppleseed? That's this part right here, the confirm box and since that's not me, I'm going to go ahead and say cancel, no, that's not me. And then it cycles back to the top of the loop and re-prompts us for my correct name, so I'm going to go ahead and type in my right name, Jason Millhouse and hit OK. Now it says are you sure your name is Jason Millhouse? Which it is so I'm going to go ahead and hit OK and it says sup Jason Millhouse. And I can close that box out and notice no more popup boxes up here. That's because internally the gotName variable is now true and so, the loop will exit and the popup boxes will cease appearing. This is a very common way to use built-in popup windows to retrieve and ensure correct information.
The Desert of Declarations
Intro to Functions
From the labyrinth of loops To the variable valley We'll see the cliffs of value first JavaScript's right up your alley Built ins, bluff, files falls Or ray archipelago Declarations in a desert where you'll find out How far you'll go Learn the program, take a ride Buy a ticket, step inside All aboard are at the station to increase your education Bon voyage and skinny dip As long as functions you don't skip On this the JavaScript Roadtrip So, those are some of the functions that JavaScript has built into directly for you but happens when you want to build your own functionality? That's the glory of computer programming, right? We want to build what we want, so in this level we're going to teach you how to build your own function declarations in this level four, the Desert of Declarations. First of all, what's a function for? Well, if we give a function some input it will do some work with on that input, some stuff to it and then it will output something on the backend of the function as a result. A function will solve problems for developers. It will do something step by step that we need to do repeatedly. Here, let's take a look at a basic function that's going to sum together two cubes. We'll call it the Sum of Two Cubes. The first step would be to get two numbers, so let's say we had four and we had nine. Then we would cube each number as the next step, so four cubed would be 64 and nine cubed would be 729. The third step in our function would actually be to sum the cubes together so we would get 64 plus 729 and that will give us 793. The last step which is of course important is to return the answer from the function, so we get 793 as the output of our function. So, what are these steps if we were to write code for them? Let's see some syntax for finding the sum of our cubes. Well, the first step of getting four we would establish a variable, let's call it A, and set it equal to four. Then we would do the same thing for nine but we would establish the variable as B. Then when we want to start cubing the values we'll start with four cubed equals 64, we'll establish a variable called aCubed and set that equal to A times A times A. Then we'll do the same thing for bCubed. Ultimately we'll make a variable called sum and add aCubed and bCubed together. So, ultimately at the end of our coded function we would have 793 as the output. Now, the cool thing about functions is that they are very reusable and that makes them very useful. We can wrap our code in a function that will allow us to reuse it frequently. Here you can see when we put four and nine into the function we'll get 793 as the output but when we put five and six into the same function we get 341. Now, let's look carefully at how to build a function with syntax in JavaScript code. We'll start our function with the actual keyword function. We'll also need two braces that enclose the entire function into a code block. Next we need to title the function. We'll call ours sumOfCubes and then we need a set of parameters that are enclosed in parentheses. Here because we have two inputs to our function we have two parameters, A and B but you can have just as many parameters as you want in any declared function. You can think of these parameters which are just basically our inputs to the function as the materials that the function either uses or does work on to produce the output you're looking for. Inside the braces of course the function will actually do some stuff. That's what we want the function to do and then at the end of the function we'll return something or even a nothing from the process. That return keyword tells the function okay, you're done, go ahead and exit and give us whatever follows the return keyword. An important thing to note about the return keyword is that you'll often see it anywhere inside the function because it can be used to instantly exit at any time. Here, however, we want it at the end of our sumOfCubes function. So, now let's actually build out our sumOfCubes function. Remember our four steps that we made? Let's see where they fall inside the syntax of our function. If we were to get two numbers as our first step, those are the parameters which get passed into the function when it is called. The second step would be to cube each number so that's going to be a process we do inside the function body. Then we will sum the cubes, that's another step we'll do in the function body and at the end we'll return that sum and that's our final step of returning the answer. So, now let's transfer in the actual syntax into those steps. While our parameters don't change, they'll still be A and B. Once the parameters are actually passed into the function they can be used at any point in the function's process. And of course our next step will be cubing A which you can see A cubed equals A times A times A followed by cubing B with the same procedure and then a sum where we add aCubed and bCubed together and then we will return that sum value from the function. Now that we have built our super cool sumOfCubes function we can call it by using the function's name followed by a set of parentheses within which we place the parameters for our function. Here when we place our four and our nine into the sumOfCubes function, we get a 793 instantly returned. Now, we can do a lot of things with our sumOfCubes function. We could use it in an assignment expression. So, if we wanted to make a variable, let's call it mySum and then we call sumOfCubes let's say on five and six and then try to alert our mySum variable after that calculation to the screen we would get 341 alerted to our user. Now that we know how to build a function let's see if we can also put in a little bit of efficiency into our functions because being concise helps us with memory and storage operations. Our function works great but we've made three unnecessary variables that all have to be allocated in memory. Let's see if there's a way to get rid of those. Well, first of all, we've made a sum variable that's aCubed plus bCubed. Why don't we just return aCubed plus bCubed? The return keyword will evaluate that expression and return it. Now we don't need a sum variable anymore. Well, if that's true, we don't need a bCubed variable. We can just put B times B times B in place of bCubed and you can probably see where that's going. Because if we don't need a bCubed variable then we don't need an aCubed variable either and we can just write A times A times A. So, now we've got one statement that says return A times A times A plus B times B times B which is what we wanted to do in the first place. Now we've eliminated three different variables and simplified our function. Now, as you saw before, we can call our sumOfCubes function with two numbers passed in as parameters but we can also pass in expressions as parameters. JavaScript will go ahead and evaluate and simplify those expressions before calling the actual function. So, you can see here that if we called the sumOfCubes with two expressions as parameters, one plus two, and three plus five that would be the exact same thing as calling sumOfCubes on three and eight and of course we would get a 539 as the output. We can also use variables as parameters. Here you can see we've established a variable called X that we've set to three and then we've used X inside the parameters in a sumOfCubes call. So, this particular call of sumOfCubes would be the same as sumOfCubes six and 12 because X is three and so, we would get an output of 1,494.
Problem Solving with Functions
So, we've done the simply function, now let's try a more complex function. Let's make a function that counts the Es in a user-entered phrase. We will combine the built-in functions of level five with our declared function of level six. Let's call our function countE and in this particular function we'll have no parameters. That often happens in JavaScript code. The first thing we'll do in our function is we'll ask the user for a phrase to check. And then if that particular entry is invalid the first thing we'll do is alert the user and then we would exit the function with a failure report. As you know, we'll exit the function by using the return keyword. Otherwise if the entry is valid, we'll go ahead and start counting the Es inside the user's phrase. The first thing we'll do is we'll make a counter variable for the Es. Then we'll have a for loop that goes over each character in the user's entry. If that particular character is a capital E or an E we will increment our E Counter variable. Finally, we'll alert the amount of Es in the phrase and return a success from the function. Okay, so let's start coding. We'll establish a variable called phrase and we'll assign to that the results of a prompt function that asks which phrase would you like to examine? Then if that entry is valid, we will know it because the phrase variable is a string. So, we say if the typeof the phrase is not a string, we will alert to the user that that's not a valid entry. And then return a false which will instantly exit the function. Our otherwise becomes an else which is where we will actually count the Es. So, first of all, we'll establish a variable called eCount that gets set to the value zero because we don't know how many Es are in our phrase. Then we'll make a for loop which will start at the very first index of the phrase, proceed all the way through all the characters of the phrase incrementing the index through each loop. Inside the loop we'll have a complex conditional. Remember those? Where we check to see if the character at the current index we're looking at is either a lowercase E or whether that character is a capital E and if that is true, if we get a truth value out of that complex conditional, we'll go ahead and increase the eCount variable. Once that loop is entirely complete we will have in our hands the amount of Es in that phrase and we can tell the user with an alert method there are however many Es in that phrase. Then we can return true which will instantly exit the function. So, let's see this in action. So, now if we were to call our countE function, notice with no parameters, we would get a small popup window from our website that says which phrase would you like to examine? So, let's do excellent elephants which has a few Es in it as you can see. Once we've entered that phrase, the countE function will proceed and we will find that there are five Es in excellent elephants. Now, let's take a little bit closer look at how that works internally. So, if we want to trace our E counter we know that we're going to start at index zero. The first that will happen is that we check whether the index is less than the length to make sure that we don't go over the edge of the string. For index zero of course that's true and the character at that index is a capital E, so when we ask the question is the character at that index a capital E or a lowercase E we get a truth value from our complex conditional and so our eCount is instantly turned to one. As the loop continues, this procedure will occur for every character including spaces and punctuation and when we finally get to the index that is just past the end of the string we'll get a false value from the loop condition and stop the loop. The function will instantly return an eCount of five. So, now that we've tackled a more complex function we will wrap up our function level with an examination of local and global scope inside JavaScript. Let's say we've got a program and the program has some variables and it also has a couple functions. You can see our variables are X and Y and our functions are add and lower subtract. Now out here in this space in the main program the scope is called global which means that variables declared there are potentially accessible from any place even within the functions below. Inside the functions the scope is called local and all of the variables that are declared inside the functions are only contained within those functions. You can think of global and local scope as being like the global planet Earth having many nations and within each of the nations they have their own government and their own way of doing things. An important thing to know about functions is that they will always create a new local scope. The variables that are declared inside of a function will stay in that function. So, let's take a look at this tiny snippet of code here where we outside the function declare a variable and set it equal to six. But then inside a new function add we rename a new variable X and set it equal to the parameters A plus B. So, you can see that I've got a variable keyword on that X. When that happens in a local scope an entirely new variable is created with the name X that is only accessible to the function block for add. So, here you can see that if we called the add function and passed in the values nine and two, add itself would return 11 but then if we logged out the variable X we would still get six and that's because the internal variable X that got set equal to A plus B did not modify the variable that's on the outside of the function. In JavaScript however, we need to be careful because if we don't declare the variable X, JavaScript thinks that you mean the global variable on the outside of the function. So, you can see in this second snippet of code that we've still got our variable X declared outside the function but inside we no long have declared a new variable X and instead just use the name X. So, you can see here that if we actually called the add function this time with nine and two, yes, the add function would return 11 but when we log out the X variable, it's value has been changed to 11. It's always important to declare your variables carefully and know the relationship between the local and global scopes in JavaScript. So, coming back to our earlier program, if our program had the variables X and Y and the functions add and subtract we know that the add function would create its own local scope with the parameters A which is local to the function and B which is also local to the function. Then inside that add function we would have a variable called X that would be local as well to the function. Now take a look at the subtract function. It also have local parameters A and B but when it uses the variable Y it is the global variable Y that it modifies. How can we tell that in the code? There is no variable keyword next to the Y inside of subtract.
The Array Archipelago
Array Ho!
From the labyrinth of loops To the variable valley We'll see the cliffs of value first JavaScript's right up your alley Built ins, bluff, files falls Array archipelago Declarations in a desert where you'll find out How far you'll go Learn the program, take a ride Buy a ticket, step inside All aboard, you're at the station To increase your education Bon voyage and skinny dip As long as functions you don't skip On this the JavaScript Roadtrip All right, road trippers, we are coming down the home stretch and now you are masters of the declared function and you can build your own basic functionality. Pretty cool, huh? And now we're going to move to exploring how we can put a list of data inside of one convenient variable. Welcome to level five, the Array Archipelago. So, we're back on our train and what if we wanted a passenger list for our train car? How would we structure a list of passengers inside our new train system? Well, taking a look inside of our trains.js file we could make a function. We could call it makeList. And you can see that it has an empty set of parameters and inside the function we could make a whole bunch of variables, one for passengerOne, one for passengerTwo, one for passengerThree and so on and so on but what if we have 60 passengers? And then what if they changed? This would kind of suck just a little bit, right? So, we need to find a way through one variable to access an entire list of people that are passengers on our train. For that we have a very special data structure called an array. An array is a data structure that we can reference with a variable name and it has automatically indexed positions. Let's take a look at a six-cell array of passengers. Here you can see a bunch of people that are passengers on our new six-cell train. Just like strings, arrays have have indices that are zero based. So, if we referenced cell zero here we would get Gregg Pollack who's in the very first cell of the array. And in cell four despite his excellent mustachio figure we have Jon Friskics. Even though we currently have a picture array we could also have an array of strings that has their names. We can build a string array very easily and we can have easy access to its contents using indices. So, if we wanted to build this six-cell string array we could make a variable called passengers and then using a set of square brackets build an entire list of the strings that we would like inside of our array. When the array is built internally it will automatically place each of the strings in order into each of the array's indices in order. If we wanted to access any particular index's value we would use the notation for example here passengers and that says to return the value at index five. If we did that here we would get Ashley Smith which is obviously in the very last cell of our array. Another cool thing about arrays is that we can reference and change the contents of specific cells using the same indices that we used to just get the contents out. If we wanted to change the value contained at any particular index, we would use the same style of notation to reference which cell we want to deal here. Here if we wanted to place Erick Allam's name into the second cell we would say passengers and set that equal to Eric Allam as a string. Again, this particular syntax says go over to the index two and change the value that's there to whatever comes after the equals assignment sign. Just like strings we could access the length of arrays if we type the variable's name and the .length property. Having done that, we see that this returns a value of six because there are six cells. Arrays come with a whole bunch of methods that you can use to manipulate the contents of the array as well as manipulate the length of the array. Here we'll look at the pop method. Not only does pop delete the last position in the array, in this case it would be Ashley Smith and in the fifth cell but it will return the string as a value. After we call the pop method, we can see here that our array now has one less cell. Well, if we've taken piece off the back of an array we should also be able to put a pice back on. We can do that with the push method. So, if we start here with our previously shortened array and we call the push method on our our array passengers using the string Adam Rensel, we see that Adam gets added to the very last cell in the array and the length is automatically increased. An interesting thing about arrays is that they can hold anything, strings, values, variables, even other arrays or combinations of them all. So, here in our first array combo one, we've got one, fish, two, fish and that is a string, another string, then a number and then a final string. Arrays can also accept variables when they're being built. If we established a variable called poisson and set it equal to the string fish we could then use poisson inside of this second comboArray where we use red, poisson, blue, and another poisson and then when the array actually gets built, poisson get replaced with its evaluation which is fish. So, are you ready for a mind melt? Well, arrays can hold other arrays as well. Check out this arrayOfArrays. This arrayOfArrays includes both combo one and combo two. When the array actually is built, the contents of combo one and combo two gets placed inside arrayOfArrays, the entire contents of combo one go in the first cell of arrayOfArrays and the entire contents of combo two go in the second cell. You can see that when we use console.log to print out the arrayOfArrays to the console we can see that it returns an array that contains two arrays each of different length. Notice also that the names of combo one and combo two have disappeared inside arrayOfArrays. So, now we can use the variable arrayOfArrays to access an entire array that it holds. You can see that if we use the console.log method on arrayOfArrays it will move over to the second cell of the array and retrieve the entire array present there. Then we get red, fish, blue, fish as a result. Sometimes this type of array is called a two-dimensional array. That's because we have the cell of the largest array, arrayOfArrays and then we have the cells of the internal arrays as well. We can select individual components of the internal arrays here. You can see that if we use two brackets and we tried to console.log out arrayOfArrays one and then two in the second bracket what happens is we look in the second cell of arrayOfArrays and then in the third cell of that array we find there which gives us blue. Similarly if we used the log method on arrayOfArrays we go to the first cell of arrayOfArrays and then this second cell of the internal array and we get fish.
Searching Arrays
Since arrays are in their very nature list oriented, you might expect that we could use a loop to iterate over all the contents inside of an array and it's true, they help us out very much. Let's take a look at this numberList. So, you can see here that we have 10 numbers in a new array called numberList. If we wanted to iterate through every one of those numbers in the array we could establish a for loop that starts at the very first index, notice that that is zero and proceeds all the way through the very last index, notice that that is nine even though the length of the array is 10. Then we could use the console.log method to produce a string that says the value in cell I, notice we're referring to the particular index that we're at is numberList to the actual contents of the cell at index I. Remember, not to confuse the index which is the position we're at with its actual contents which is the value. So, let's kind of take a look at how this works in action. So, when we start at I equals zero, our very first index, we'll ask the question whether I is less than the length of the entire array and of course that's true and then we retrieve the value at numberList which is two and our printout becomes the value in cell zero is two. We do the same thing when we get to index one. We ask the question is I less than numberList.length? Yes, it is and the value in that cell is five and so, we get the value in cell one is five. That procedure repeats throughout the entire loop until we get to the actual length of the array when our question becomes false and we stop the loop. So, we've looked at arrays that have a whole lot of contents in them and you might ask the question can you have an array with no contents in it or can you have an array with cells that are empty? Yes, you can. Let's take a look at that. We can use the undefined value to create empty cells because the undefined value just means no contents. Looking in our existing numberList array if we wanted to make cell five empty we could just use our regular cell reference notation with numberList five and set that equal to undefined. That instantly makes that cell the fifth index in the array empty. So, now that we know how to erase contents from arrays, let's see if we can write some code that will do two things. We want to count the even numbers in our numberList as well as erase the odd numbers. Ready, here we go. So, we've got our numberList array already and we know that we're going to need to count our even values so we'll set up a variable called evenCount that will gradually count the even numbers in our array. Then we'll start our for loop that progresses through the array just our previous loop did. Inside the loop we need a way to check if we have an even number. If our reference value divided by two has a remainder of zero, we will increase the evenCount variable because we have found an even number. But otherwise if we don't have an even number what do we have? An odd number and so, we should erase that number. How do we do that? Well, we say that the numberList in other words, the value at the current index should be undefined and once we have done that, that value is no longer there. At the end of this code we could also log out the current even count and that would be five. Let's take a look at that code in action. When the index is zero, we check to see if we are still within the array length and we are, so then we get the numberList value which is two and then we check to see if two is an even number. Two of course is an even number and so our evenCount would advance to one. This procedure reoccurs throughout the entire array, erasing odd values and counting the even values. When we finally get to the end of the array the loop stops and you can see that we have an evenCount of five. What if we were to now log out our changed numberList? What would that look like? Taking a look we see here that our array kept all of our even numbers and erased all of the odds but still left empty cells where the odds used to be. Those are represented here by the undefineds. And to show that the size of our array hasn't really changed at all, we can log out that using the .length property to see that the array is still of length 10. Now that we know significantly more about arrays we're going to build a function that solves our initial problem of building a passenger list. So, here's our function called addPassenger and we know that that function is going to need two parameters. The first is the passenger's name that we're adding as well as the array of passengers that we want to add the passenger to. Inside our function we know that if the list is empty, we may as well just add the passenger to the list. We're okay with that. Otherwise we know the list is not empty and so, we need to find the exact right spot to put the new passenger. So, what we do is we iterate over all spots in our passenger list and if the current spot is empty we want to add our current passenger to that spot since it's empty and then we want to exit the function. Otherwise if we've gotten all the way to the end of the list and the passenger still has not been added we need to add that passenger to the back of the array increasing its size. So, that's our pseudo code. Let's see if we can get some real code in its place. The first thing we know is that if the list.length property is zero then the list is empty, right? So, we can just push the name of the passenger onto the list. Otherwise the list is not empty so we know we're going to need a loop to check for empty spots. Here's our loop. It looks just like the other one. We will process through the entire length of the array looking for empty spots. But how do know if it's an empty spot. We have to use our undefined trick. If the current spot we're looking at list I is the undefined value we know it's empty. So, therefore we can place the name of the current passenger being added in that cell. Then we can immediately exit the function because we're done adding that passenger. Notice that the return keyword here has nothing to follow it. That's totally acceptable when you just want to exit the function with no value. Now, we also have an else if statement that follows that checks to see if we have reached the very last cell of the array. If we have, what do we know? We know that we have not reached an empty spot yet for this array. So, we can go ahead and push the current passenger onto the back end of the array increasing in size. Then at the very bottom of the function we'll put one final return list so that we can ensure that the modified list has been returned to the program. Good, so now we've got a passenger adding function. How awesome but let's see if we can build a passenger list from scratch and start adding some passengers to it. Here we go. So, we'll start a variable called passengersList and we'll set it up as an empty list. We can do that with just two brackets. Then we'll call our addPassenger function and we're going to add Gregg to it. So, you can see our very first parameter is Gregg Pollack as a string followed by our newly created but empty passengerList. What gets returned is a new array with Gregg Pollack as the very first and only cell. Then let's add Ashley Smith using the same exact procedure. What gets returned is our modified array that has Gregg in the first spot and Ashley in the second spot. We could do it one more time and put Jon in the third spot. Awesome, we've got a full list of well, three passengers. So, let's see if we can now delete some passengers by building a delete passenger function. Here we go. So, we've got our deletePassenger function. It's also going to take in a name and also the list. You can see that we'll check if the list.length is zero. That means there's no passengers in this list so how could we possibly delete anybody from it? And all we need to log out is that the list is empty. Otherwise we'll start our loop that checks the entire contents of the array. Inside the loop if the cell that we're currently checking is the name that we're looking for we'll go ahead and set that cell to be empty having removed the passenger. Then we can return the list because we don't need to look for that passenger anymore. Otherwise we have an else if here that checks to see if we have arrived at the very last cell. If we have arrived at the very last cell but we have deleted no passenger that means that the passenger does not exist in our current list and so we can report with the console.log that the passenger was not found. At the very end we will also return the list. Why? Because if we've returned the list somewhere else in the function, we know that our exterior program is expecting some kind of list to be returned so it's good practice to make sure that we return the list whether it has been modified or not. So, now we've built both an add passenger list and a delete passenger list. We have full control of our passenger list. Let's go ahead and mess around with it. First, we'll take out Ashley Smith from our existing list, so our loop seeks through the array, finds her in the second cell and erases her from that cell. Notice now that we get a return of an array that has the second cell empty. Then we'll add Adam to the list. Notice that our addPassenger function finds the very first empty spot and places Adam inside that spot first. Then we'll try to delete Ashley again. Uh-oh, she's not found. That's of course because we deleted her before. Then if we try to delete Gregg, he'll be removed from the very first spot and then if we try to add Jennifer, she'll be placed in Gregg's old spot, the first cell.
Course author
Jason Millhouse
Jason has been teaching since he was a kid and has racked up a bunch of Education degrees since then. A glutton for punishment, he's nearly finished with a Computer Science degree, too. He's built...
Course info
LevelBeginner
Rating
(15)
My rating
Duration1h 26m
Released10 Sep 2013
Share course