What do you want to learn?
Skip to main content
by Mark Zamoyta
Start CourseBookmarkAdd to Channel
Table of contents
Introduction and Our First App
Storing Information in Variables
No matter what kind of application we're going to be developing, we're going to need to be working with information. And when we're programming we store information in variables. Let's see what a variable is. Let's say we're going to create a GPS application, we just simply want to track a car, or a person, or something like that. What's the key information we're going to use in this application? Well we're going to need to keep track of the longitude and the latitude of whatever we're tracking. And if we're tracking a person, we're going to need to know who that person is. And if we're tracking a vehicle, we're going to need to know what that is. So these four items, longitude, latitude, person, and vehicle are all variables that we can use in our program. And a variable is simply a word, or some kind of similar symbol. Let's look at another example. Let's say we're going build a rocket ship application. It would be good to know the name of the rocket, and it would also be good to know the fuelType. And you'll notice here for this variable name, it begins with a lowercase letter for fuel, but the second word, Type, is in uppercase. This is called camel casing, because there appears to be a bump in the middle. And this is very common when you're creating variable names. Another example of a variable could be the launchLocation, that would be the city where it launches from, and possibly maxSpeed for a maximum speed. And again, this style of casing for our fuelType, launchLocation, and maxSpeed is called camel casing, and it's very common. If we're going to create a dinosaur game we might want to keep track of the score in a variable name, the level that the player's on, if it's a multi-player game we might want to keep track of the playerName, and the dinoSpeed, the speed of the dinosaur. So let's see how we can create these variables in an application and work with them. So I'm here at Plunker and we're looking at the Hello World application we created in the introduction to this course. We have the Console on the right side, that's where our output will show, and I'm going to hide the panel on the left here. We're working in script.js, but we don't need to be reminded of that. So if we execute this we get our Hello World that we've seen earlier. But let's go ahead and delete this code, and the way to create a variable is with the let statement. We say let, and then we specify the variable name. Let's create a variable named productName. So now we have a symbol to hold the productName, but we want to assign a product name to it. So we'll type an = and in double quotes I'll type the name of the product. Let's say we're working on a hardware store application and I'll call this Hammer. And I end the line with a semicolon, just like we did in the Hello World application. So now we have a variable, and we're going to be working with variables all the time as programmers. So just to look at this again, we use the let keyword, and then we create our variable name, productName in this case, and then we assign the string Hammer to productName. And notice that the string is in double quotes. And we'll see more about quotes soon, but now that we have this variable called productName what can we do with it? Well let's write it out to the Console. I'll enter console.log and I'll put the productName variable here. And if we look at our output we can see that it shows Hammer. Generally you want your variables to begin with a lowercase letter, like in this case. And you want the name to be descriptive of what you're working with. For example, if we had a variable that was simply named p that would work fine. Let me clean the Console here. And we can see that this code works as well. We get Hammer showing in the Console. But to create a variable that's just called p might be confusing. As the code gets more complex you'll forget what p stands for, so I'll just undo this. And now we're back to having a productName. And most likely you're going to be working with a lot more than just one variable, so one thing we can do is we can create a second let statement. We'll call it let productId = and we'll call it H123, we'll just give it a generic ID number here. And if we wanted to print out the productId as well, we can specify a comma after productName and the second variable name, productId. And we get Hammer H123 showing. Now there is a shorthand for this, instead of having lots of let statements up here, we can actually separate these with a comma. So we have productName = Hammer, productId = H123. And you can see that we get the same output as before. And like I mentioned in the introduction, all of these spaces and new line characters are called whitespace, and it really doesn't matter if you put them on the same line, or separate lines, or separate them by one space, or lots of spaces, as you can see here we still got the same output again, Hammer H123, but it's just easier to work with if we line up these variable names. So this just simply makes the code a bit clearer to see and work with. So that's the very fundamentals of working with variables. In the next video we'll take a look at what happens if we do something wrong. We'll see some of the error messages we get and we'll see how to fix those.
Understanding Code Errors
Strings and Numeric Variables
Starting Our Blackjack Application
Types and Arrays
Type Basics: Strings and Numbers
We've seen string types and number types, now let's take a look at Boolean types. There are two Boolean values. The first one is true and the second one is false. And notice that these two values are all lowercase. If you use them in uppercase you'll get an error. And we can take these values, true or false, and assign them to a variable. Let's see that in action. Let's modify this so value = true. We log out value, which is true, and we log out typeof value, which is boolean. Likewise we have a value of false. And that shows false and boolean. Another name for a Boolean value is a flag. An example of a real flag you might have in a program, let's say we're creating a video game, would be something like, isMultiplayer. And that would just let us know whether or not the game is multiplayer or not. Here it's set to false, but if the user did something and wanted to start playing in multiplayer mode this would somehow get set to true. Or maybe in shopping cart application you may or may not have to calculate sales tax, so you could have a variable called calculateSalesTax. And we'll take that variable and log that one out. I'll copy it and paste it into our log statement. And we get true, and again, the type is boolean. So that's the simplicity of Boolean values, they're either true or false. And later in this course we'll work with Boolean values a lot more, mainly when we start getting into conditions and logic, which we'll find out about soon.
undefined and null
Storing Multiple Values in Arrays
Adding Arrays to Blackjack
Let's see how we can use arrays in our Blackjack game. Here's our game from the last module. And I'll just run this quickly here. And I'll set the Console to the bottom. And we can see we get some messages, Welcome to Blackjack!, You are dealt: Ace of Spades and Ten of Hearts. And if we look at our cards here we would have to list out every card in its own variable, but for now let's create an array. We'll specify let deck, for deck of cards, equal to an empty array. And we don't need these cards so I'll remove those in a second, let's list out a few cards in this deck. We can use the Ace of Spades, and we can list these line by line. Remember that we're free to use new lines and spaces wherever we'd like. And then I'll specify a Two of Spades and Three of Spades. Now this would be really tedious to print out all the cards this way, but in the next course module we'll see how to do that easily. But for now, an array is getting us a step close to what we need. So I'll delete these two variables here, card1 and card2, and let's create a variable that holds the player cards. Let playerCards = and we'll create an array. Because a player can have 0 or more cards, but usually you're dealt two cards to start. So let's have the two cards be deck, index 0, that'll be the Ace of Spades, and also deck index 2, which will be the Three of Spades. Remember, Ace of Spades is index 0, Two of Spades is index 1, and Three of Spades is index 2. And we'll log these out. Instead of card1 and card2 we'll show playerCards 0, that'll be the first card, and playerCards 1, which will be the second card. So now we can see the messages You are dealt: Ace of Spades and Three of Spades. And if this a little confusing let's just walk through this again. We're looking at playerCards 0, which is right here. And deck 0 refers to Ace of Spades. So that's why we get Ace of Spades here. And walking backwards we have Three of Spades, that came from playerCards 1, which came from right here, deck 2, which is this element of deck, Three of Spades. So we're a step closer to working with a real Blackjack game. The next thing we need to do is create a real deck of cards. And in order to do that we need to be able to create loops, and we'll see how to do that in next course module, but for now let's cover everything up with a summary.
Conditionals Using if()
if … else
switch and case
There are two more keywords called switch and case. We can create switch statements, which is an option to using if statements, let's see what I mean. Here we have a switch statement. First of all, let's initialize the variable state to TX for Texas, and then we specify the keyword switch, and in parentheses we specify a variable name, or some other value. In here we're specifying state, and then we have a bunch of case statements, the first one is case NY. So if state were equal to NY this code would execute. And in the case that state was equal to TX this code would execute, and in fact it will execute because we're initializing state to TX for Texas. And at the end of the cases we usually have a default block. If state were equal to anything other than NY or TX, it would execute this code here. You'll also notice that each case block has a break statement. This is very important, and it's the cause of many bugs when working with switch. If you leave out this break statement code execution will drop through to the next statement, and we'll see that when we start working with Plunker, let's go there now. So we'll start off by letting state equal TX for Texas and we'll have an empty switch statement. We'll perform our switch on the value of state. And we haven't set up any cases or our default block, so let's do that now. I'll set up default first and we'll log out unknown. And always remember to put the break statement, even on default. It's not necessary on a default, but a developer might enter something after default in the future. And when this executes you can see that we get unknown as the value. Now let's add some case blocks. Case, let's put NY for New York. We'll log out New York. And remember to break. Again we get unknown because this case did not match, so the default executed. Now let's add a case for Texas. I'll log out Texas, and I'll break. And you can see that we get Texas in the Console. So now we have a case that matches the value of state. So this code will execute. And we could have multiple lines of code here. I'll just type Austin. And we get Texas and Austin showing up. And, like I mentioned, one of the more common bugs is to forget to put your break statement. So let's take this break statement out and see what happens. We get the result of Texas, Austin, and also Unknown prints. So this falls through from this case statement to default. And in very rare cases you actually might want that to occur. And if you did want that to occur you should probably let future developers know about that. So let's put a comment in here. Allow fall through, and that will just let future developers know that you coded it this way on purpose. But in the vast majority of cases we always want to break at the end of a case statement.
Looping with for()
Sometimes you want to execute a block of code over, and over, and over again. And this happens a lot when we code. You might want to loop through all the cards in a deck of cards, or you might want to loop through every item in a shopping cart, and as a professional developer you'll be working with loops all the time. And one popular type loop is the for loop, let's look at that. Here's an example for a loop. We use the for keyword, and then we have something very complex looking within parentheses. And let's break this down. The first part of this code runs before the for loop even executes. So what we're doing is we're creating a new variable i and we're setting it to the value 0. And i is the traditional value to use in a for loop. You don't have to use i, but you'll see it often. I can stand for index or iterator, but it's just simply a variable name, i. And then we have a semicolon to separate that from a condition. Here the condition is i is less than 3. And is i less than 3? Yes it is. And because it is we'll execute this code block. Again we have the beginning and ending curly braces to specify the code block, and we'll simply print out i. When this code block finishes execution we go to the third part of the for loop, which is i++. We haven't looked at the ++ operator yet, but that simply adds 1 to the variable. So at the beginning i will equal 0 and after i++ executes i will equal 1. And because we're looping we go back to our condition. Is i less than 3? Yes it is. So now we'll log out 1. Then we'll execute i++ again, so i equals 2. Is i less than 3? Yes it is. So we execute the code block. Then we'll go up to i++, i is 2 so i++ will be 3. Is 3 less than 3? No, it's not, that's false. So now the loop is finished. Execution will continue after the code block and we'll never execute that code block again. So you can see the comment I put here, this for loop prints out the values 0, 1, and 2. Let's go to Plunker and see a for loop in action. So I'll use the for statement, and parentheses, we'll create a variable i, and we'll initialize it to 0. And remember that semicolon. I will be initialized to 0 just once, but the condition may be checked several times, so let's add a condition. Let's say i is less than 5, and we'll say i++, we'll increment i by 1. And then we specify the code block that we want to execute, and I'll simply print out i. When we look at the results we get 0, 1, 2, 3, and 4. We initialized i to 0 and we logged it out, then we incremented i by 1, and i was a 1 is less than 5, so we logged out 1. And that continued all the way until i was 4 and we performed an i++ on that, where i became 5. When i became 5, i is less than 5 became false, so that was the end of our program. Looking at the result again 5 never prints out. As soon as this condition is false the loop is complete, no more code within the loop will execute. And we can initialize i to anything, let's initialize it to 3 and see what happens. Let me clear out the Console. Now it just prints out the values 3 and 4. Also we could change our condition to be anything, i is less than or equal to 5, and let me just clear out the Console again so we get a good look at it. We get 3, 4, and 5, because when i is 5 the condition is still true, it's only when we perform an i++ and i becomes 6 that the condition is false. So we don't get the 6, and the final number printed out is 5. For loops are something that you're going work with very often, so it's good to get a lot of practice with them. We'll be using for loops later in this module to create a deck of cards. And there's another type of loop called a while loop and we'll see that in the next video.
Looping with while()
Adding Loops to Blackjack
Let's add some loops to our Blackjack game. We can use loops to easily create a deck of cards. So here we have our Blackjack game from the last module. And you can see here that we're creating deck by specifying every card in the entire deck. We only created 3 cards, but we would need to create 52. Let's use a loop to create this deck. First of all, we're going to need to loop through arrays that have the information we need. Let's create an array called suits, and I'll add each suit in the deck. We have Hearts, Clubs, Diamonds, and Spades. Let's create another array called values, and we'll add the 13 card values, Ace, King, Queen, Jack, and I'll continue it on the next line, and all the card values down to Two. So values ranges from Ace at the highest to Two at the lowest. So now that we have these two arrays. let's use for loops to create our deck of cards. We'll initialize deck to an empty array, and let's loop through our suits. In our for loop let's let suitIdx, I'll abbreviate it Idx, = 0, and then we want to execute this loop while suitIdx is less than suits.length. And then for the loop we want to make sure the increment suitIdx, so I'll add suitIdx++, and I'll add our body. Now we can space this out a little bit more if you prefer it to be spaced out. SuitIdx = 0, suitIdx is less than suits.length. And remember, suits.length will equal four, Hearts, Clubs, Diamonds, and Spades. So suitIdx will range from 0 up to 3, which is what we want. So we'll work on one suit at a time, but then we need to have what's called a nested loop, now we need to loop through the values. So within our suit loop let's have another for loop. We'll let valueIdx = 0, and then the condition we're going to be working with is valueIdx is less than values.length. And this will make sure that we cover all of the values. And we'll increment valueIdx. So this is called a nested loop, we have one loop inside of the other. And how do we push these cards onto deck? We can say deck.push, and simply push the card we want. And what is the card? It's values, and the index is valueIdx +, and I'll add a space, of, and then I'll add the suit, suits, subscript, suitIdx. So this is how we create our deck of cards. I'll remove the blank lines, and let's take a quick look at this again. We're going to loop through all the suits and for each suit we're going to loop through all the values. And we'll call deck.push, our value of suit. And let's create another loop just to make sure that the deck got successfully created. For, we'll let i for index, or iterator = 0, i is less than deck.length, i++. And we have our code block, and let's just log out deck subscript i, and let's run it. I'll open up the Console wider, and we can see that we have our big list of cards. It starts with the Ace of Hearts, goes down through King, Queen, Jack of Hearts, then it gets into the Ace, King, Queen of Clubs and so on, and then we have our Diamonds, and then we have our Spades. So looking back at the code, with these 5 lines of code right here we were able to create the full deck of 52 cards. As a developer you're going to be working with loops all the time. Here we're using cards, but some loops have thousands or maybe even millions of data items to process. So it's good to get a lot of practice with loops and just remember to avoid infinite loops.
In this module we looked at the if statement and the else statement. We can conditionally execute code if a condition is true or false. We looked at the values of truthy and falsy. Things that are false are values such as 0, an empty string, null, undefined, and that type of value. A truthy value is anything that's not falsy, and these are used in conditions. Next we looked at the switch and case statements. Based upon a value that we're switching on we can execute one of many case statements. The thing to remember is to break out of each case statement. In a rare case where you don't need to break out and fall through, you should at least comment it for any future developers looking at the code. Next we looked at for loops. And here's an example. We use the for keyword, we initialize something, here we're initializing a new variable i to equal 0, and then we set up a condition. The condition here is i is less than 5. So the code block, right here, will execute, as long as i is less than 5. And at the end of each code block, this part of the loop executes, and we increment i. And then we looked at while loops. While loops consist of the keyword while and a condition. And the important thing to remember with while loops, or even for loops, is that we need to avoid infinite loops, they cause a lot of problems for developers, and as we saw, they even shut down your browser tab. So now we know a lot about program flow. Not only does the program flow from the top of the source file to the bottom, but we can use if statements, switch statements, and loops, such as for and while, to alter the flow of our code.
Hi, my name is Mark Zamoyta, and in this module we'll be talking about functions. And a function is simply a block of code that we can execute over, and over, and over. So we'll be learning function basics. We'll see how to use the function keyword in order to create a function. We'll see how to pass information into a function, and then get some information out of the function. We'll take a look at function scope, which has to do with using variables within functions. And we'll wrap it up by adding functions to our blackjack game. So let's get started and see how we can create our first function.
We've seen how to create a code block when working with if statements, for loops, while loops, and now we're going to look at code blocks with functions. Sometimes you want to be able to execute code at any point in your program, and that's what a function is for. Let's see how we create one. To create a function we use the function keyword, and then we give the function a name. Here the name is showMessage. Next we have opening and closing parentheses, and we'll see what those are about soon, but for now we still need the parentheses even though there's nothing between them. And next is our code block in curly braces. Let's look at the next slide. So now we have a line of code that's going to execute as part of this function. And we could have as many of lines of code in here as we'd like, but it's important to note that we're only defining the function here, we're not executing anything. And here's how we do execute functions. Here's the function we just created and to execute it we simply specify the function name, showMessage. And it's very important that we also need the opening and closing parentheses. So as this code executes, the function will be defined, but not called. When this line executes the function will be called, and the message in a function will be logged out to the Console, and then we're calling it again. So the message is shown twice. And generally a function is a code block that you often do want to execute a lot more than one time, that's why we put it in a function. Let's go to Plunker and create our first function. So I'll type the keyword function, and then we'll give the function a name. I'll just call it myFunction, and we'll put opening and closing parentheses, and then we'll create our code block with curly braces. We'll simply log out a message, in myFunction. And as you can see now, nothing is printing out to the Console, the function is created, but it's not executing, so let's execute the function. We do that by specifying the function name with the opening and closing parentheses. And now you can see the output in myFunction. And we can go ahead and call this function as many times as we'd like. So now it showed two times. Now this function isn't very useful, it prints out the same message over and over. So in the next video we'll see how we can pass information into the function.
Passing Information to Functions
Let's see how we can pass information into a function so that the function can make use of it. Here we're creating a function called showMessage, but notice this time in the parentheses we have what's called an argument called message. And this refers to input that we pass into the function. You can think of message as becoming a variable that can be used within the function. So we call console.log and we pass it message to log out the message to the Console. Notice we're not using quotes at all here, we're working with an argument, which is a variable called message. And then when it comes time to execute this function we can pass the value to the function. So here we're passing the value First Message, and that does need to be quoted in a string, because it's a text message. In the second call to showMessage we'll pass it the value Second Message. So when this executes the Console will read First Message, Second Message. But what if we wanted to pass more than one piece of information into the function? Well here we can see two arguments. The first argument is the message and the second argument is anotherMessage. And notice that these are separated by a comma. When we call console.log we log out both the messages, message and anotherMessage. Looking at how we call this function now, we call showMessages, passing it the first argument and the second argument. Let's go to Plunker and see this in action. So here's our code from the last video, let's just call myFunction once. And we'll pass it an argument called message. And you can think of message as a variable that we can use in the function now. So I'll console.log message. And when we execute my function we'll pass it a message. We'll just say Hello. And we get Hello showing up in the Console. And we could do whatever we'd like to do with message in this function. Let's say message = message + a new string, World!. And it logs out Hello World!. And we can go ahead and add as many arguments as we like, we just separate them with commas. Let's just call the next argument favoriteNumber, and then we'll log out message, favoriteNumber. Now you'll notice that when we call myFunction we're only passing it one argument. So the second argument is undefined, and you see it right here in the output. Let's add our favorite number, let's say 42, and then we get Hello World! 42. So it's important that your arguments right her always match up with the arguments that you're using to call the function. It's a very common bug to accidentally change the order of the arguments, or to skip one, or leave one out. So we know how to send information into the function, but how do we get information out? We'll see how to do that in the next video.
Function Return Values
We can pass information into a function with arguments. And the way to get information out of a function is with what's called a return value. Let's see an example. Here's a function called triplePlus, and we'll pass it a value, just one argument. Within this function we'll create a new variable called newValue, and we'll assign it value + value + value. And this is an example. Normally you would just do three times a number, but I wanted to show that you can create a new variable within a function and create arithmetic expressions. And here's how we get newValue out of the function. We use the return keyword and we specify whatever information we want to return. In this case we want to return newValue, which will be value + value + value. And we call this function here, we'll call triplePlus, passing it an argument of 3; 3 + 3 + 3 is 9, so this whole function call will be replaced by the number 9, and that will get logged out to the Console. And that might seem a little bit strange how a whole function call gets translated into a single value, so let's go to Plunker and look at some examples. So let's change this around a bit from the last example. We have myFunction and we'll pass it favoriteNumber, a single number. And let's create a new variable here. We'll say let newNumber = favoriteNumber + 100. And instead of logging anything out here, we don't need to log it out we can return it. Let's return newNumber. And when we call myFunction we'll pass it 42, because we're only using one argument now, a favoriteNumber. Now you'll notice that nothing is showing out to the Console, because we don't have any logging statements. One thing we can do is assign myFunction to a variable. We'll say let result = myFunction 42, and let's log out result. And now we get what we expected, 142 is returned. Let's just walk through this and see how it works. We execute myFunction passing it the value 42. So within the function, favoriteNumber, the argument, will be assigned the number 42. And then we take favoriteNumber and add 100 to it. And we'll assign that result to this new variable called newNumber. So at this point newNumber = 142. Then we return newNumber. So our function call, you can think of it as being replaced now by the number 142, which gets stored in result. And we log out the result 142. So at this point, it's a good idea to get a lot of practice passing arguments into functions and getting the return values out. Going to Plunker and doing a lot of experimentation is a great idea.
Next we're going to look at something called function scope. And scope has to do with the use of variables within functions, or code blocks. If we create a variable in a code block, that variable will not exist outside of that code block. Let's see an example. So here we have our triplePlus function from earlier. We create this newValue variable and return it. And notice here we're calling the function, but then we're trying to log out newValue, but newValue was created in this function. And the thing to remember is that when we create a variable in a function or in any code block such as this, the variable no longer exists outside the function. So this line here will result in a Reference Error: newValue is undefined. Let's go to Plunker and work with this. Let's take our example and add a new variable. Let's let message = Hello World!, and we can just return message. And let's call myFunction, just to make sure that the variable message does get set within the function, and let's try to log out message. You'll see that we get Uncaught ReferenceError: message is not defined. So this variable right here, message, only exists within this function. If we try to access it outside the function, we get an error. Now what if we had the variable message already existing in our code? Let's create it here. Let message =, we'll just say, First Message. And we can see when we log out message we get First Message! So this is what we mean by scope. A code block in a function has its own scope. We created a new variable called message, and we assigned Hello World! to it, but by the time the function finished executing this variable no longer exists. We go back to using our original variable, message. And that's why First Message! gets logged out.
Adding Functions to Blackjack
Now that we know how to create functions, and pass information into a function, and take information out, let's add some functions to our Blackjack game. So here's our game as it stands so far. Let me move the Console out of the way. And after we set up our data, the first thing we do is we create our deck of cards. That's something that we might want to do every time we start a new game. So let's create a function for that. I'll use the function keyword, and we'll call the function createDeck. And I'll just go ahead and take this loop here that creates the deck, and I'll add that inside the function. And one thing we might want to do before we start is clear out deck. So we'll say deck = an empty array. Then at the end of the function we'll return the deck, return deck. So notice we have a variable deck right here that we're going to be using. This is the variable that we want to clear out here, and we also want to push values onto it, but we can go ahead and make this a local variable to this function. We use the let keyword, that way we can remove the let statement here, and below the function we can say, let deck = createDeck. So we'll be working with this variable deck throughout this program, and you can see here that we are logging it out. If we look in the Console we see a big list of cards, so that's working fine. What other functions could we create now? How about a function called getNextCard to take the next card off the deck? We use the function keyword, getNextCard, and we'll work with our deck variable so we don't specify let deck to create a new variable deck, we just start using the variable deck. And we can return the variable deck.shift, that will take the first value off the deck and shift the rest of the cards down in the array. So for our playerCards right here, instead of specifying deck 0, deck 2, we can call that function, getNextCard. And also call it again, getNextCard, to get two cards. And you can see here that we're getting the Ace of Hearts and the King of Hearts. I'll just reposition the output so we can see it better. You are dealt: Ace of Hearts, King of Hearts. So there are dozens of functions that we might need. Creating a deck is a great idea, to create the deck of cards. and then getNextCard, we use that to get the next card off the top of top of the deck. And we might want a function to shuffle the deck, or to show some kind of message to the user, and actually most the work that we do accomplish in software development is done within functions. So that's all we're going to cover for functions in this course. In the next module we'll take a look at objects and what they are, but for now let's wrap up everything we learned about functions in a summary.
In this module we took a detailed look at the basics of functions. We saw how we use the function keyword, gave the function a name, used open and closing parentheses, and then added a code block. We saw how we could pass information into the functions. We give the function name, and then parentheses, and a comma-separated list of arguments. Those arguments can be any values. We saw how functions can return values. Within the function we simply use the return keyword and we specify whatever value we want to return. Next we looked at function scope. We saw how that when we declare variables within functions, those variables no longer exist when the function has completed execution. And we wrapped up the module by adding functions to our Blackjack game. So we're getting a lot closer to being able to build a real Blackjack game. We know all about data, we know all about looping, and if statements, and now we know all about functions. The next piece of the puzzle is to learn about objects. And an object is simply a way of grouping related information together, and we'll learn all about that in the next module.
Passing Objects to Functions
So we know how to create objects now, but let's look at how we pass objects to functions. We'll go straight to Plunker. Here's our code from the last video, let's add a function to it. We'll call the function changeCard, and we'll pass it a card. And in this function let's just say card.suit = Clubs. And that's all we're going to do, we're not going to return any value from the function. So our card has a suit of Hearts to start out with, and then let's call our function. We'll call changeCard passing it card, our variable right here. And then let's log our card.suit. You can see that we get back Clubs. So when we pass an object to a function, such as card right here, the function does have the ability to change that object. Even after the function completes execution the object stays updated.
Arrays of Objects
Adding Objects to Blackjack
Now that we know how to create objects let's add an object to our Blackjack game. Here's our game as it exists so far. The last thing we did was we created this deck right here with the createDeck function. But if you remember what we're doing is we're printing out a value and specifying of and then the suit, so we'll get something like the Ace of Hearts. But this is just one long string right here. It would be more useful, instead of storing a long string, to store an object. So let's create a card object here. We use the let keyword and we'll create a variable called card =, and we use curly braces to denote the object, and we end the let statement with a semicolon right here. So for our properties we'll have a suit property, so we specify suit: and then the value of the suit, which is suits, subscript, suitIdx. And we can get that directly from the string right here. Then we'll put a comma after that, and we need a value property, and we see that in our string as well, Values valueIdx. So we're creating this card object with a suit property and a value property. And we want to push that card onto the deck. So we'll call deck.push card. So now instead of an array of strings, our deck is an array of real cards with suits and values. So let's scroll down a little bit and let's clean up the code a bit. Here was a loop that we had to print out the entire deck, let's just remove that for now, and let's look at our console.log statements on the bottom. We're logging out playerCards 0 and playerCards 1. But if you look at our output we're getting a notation that they're objects, and that doesn't help us. So let's create a new function to print out the card. We'll add a function called getCardString. And we'll pass it the card, and we'll return card.value + of, surrounded by spaces, + card.suit. So that would give us something like the Ace of Hearts, and we're returning that. So instead of accessing playerCards 0, we can call our function getCardString, and we'll pass it playerCards 0, which we know is an object. And you can see the results. We were dealt the Ace of Hearts right here, and the second card is still an object, so let's call getCardString on that. GetCardString, playerCards 1. So now you can see that we have the Ace of Hearts and the King of Hearts. So we're a step closer to having a more accurate Blackjack game. Storing a card an object is the right way to go. That way we can get access to the suit easily and its value. So let's wrap up this module with a summary.
Programming for Web Pages
Setting up a Web Page
Handling a Button Click
Removing and Adding Elements
Adding a User Interface to Blackjack
Let's use what we just learned about the DOM and add a user interface to our Blackjack game. So I already modified the HTML file. You can see that now we have a header that says Blackjack, another smaller header that says by me, a break, and then we have our text area that says Welcome to Blackjack! And then we have three buttons to get information from the user. The three buttons are New Game!, when the user starts a new game, and there's a Hit! button. When you take a card in Blackjack it's called a hit, or hit me. And when you're done taking cards you can press the Stay button so that you don't get more than 21 points. So the HTML is all set up and ready to go, but if we look at script.js we have the Blackjack game from the last course module, which doesn't work with the DOM at all, so let's set up some variables to access the DOM. We'll let textArea = document.getElementById text-area. This paragraph will be the main place where we give information to the user. This will show what cards have been dealt, and what the score is, and at the end of the game it will show whether you're a winner or a loser. We also need access to these three buttons, and I'll just enter these quickly. So now we have our three buttons, New Game! button, Hit! button, and Stay button. Now at the start of the game we want to hide the Hit! and Stay button, we're not ready for those yet. So I'll write hitButton.style.display = none. And that has to be in quotes. We'll also say stayButton.style.display = none. So we start out with just our New Game! button, which is perfect, but we haven't set up any handler for New Game!, when we click it nothing happens. So let's set up a handler. NewGameButton.addEventListener, we want to listen for the click event, and we'll code a function right here. And what do we want to have happen when the user clicks the New Game! button? Well for now let's do a few things, let's set the textArea, we'll actually set the innerText field to Started. Also let's hide the New Game! button, newGameButton.style.display = none, and we want to show the Hit! and Stay buttons now. These are inline, we want them to show up on the same line. So I'll click the New Game! button, and we get the text started showing up in our paragraph, that's good, and now we have our Hit! and Stay buttons. So now we're working really well with the DOM, we can start to put together a full game. In the next and final module of this course we'll do just that, but for now let's wrap this module up with a summary.
Finishing Our Application
Hi, this is Mark Zamoyta, and in this module we'll finish our Blackjack game. We've been building it throughout the course and it's time to wrap it up so it actually plays a game. We'll start off by setting up the game, we'll clean up what we already have, set up all our variables, and make sure we have a good starting point. Next we'll shuffle the cards. We haven't seen how to do that yet, so we'll do it here. We'll see how to calculate the score based upon the cards that are dealt to the players, and we'll implement our hit and stay buttons so that the player has the option of either taking a card or staying, not taking another card. And we'll wrap it up by adding the final code to our game, and seeing the game in action, and also taking a look at some of the features that you might want to add to the game. So let's start off by setting up the game.
Setting up the Game
Throughout this entire course we've been setting up our game very gradually. So let's take a look with what we have to start with. We'll start in the index.html file, and this is complete. We have our title area, and we have the paragraph and buttons that we're going to need. And the important thing, as mentioned before, is that the script tag needs to be placed right before the end of the body, right here. That way we get access to the IDs for the elements. And looking at script.js, I did clean this up a little bit, but let's just take a look at the variables first of all. We have suits and values, those were set up earlier, and we have our DOM variables, we called document.getElementById, passing it the IDs for our text-area, new-game-button, hit-button, and stay-button. And then I added some more game variables, let's see what these are. We have a Boolean value, which tells us whether or not the game has started, called gameStarted. There's another Boolean value called gameOver, so when the game ends this will get set to true. There's another Boolean value, which tells us if the player won as opposed to the dealer. And we have the dealerCards, which is an array of cards, we have the playerCards, another array of cards, and now we have to keep track of the dealerScore and the playerScore. And as we've seen before we have an empty deck of cards, it's an empty array. I'll scroll down a bit, and we want to hide our hitButton and stayButton to start off with. And I created a new function called showStatus, and we'll see what that is in a second. Now we have our handler for when the user clicks on the New Game! button. We'll set gameStarted to true, gameOver will be set to false, and playerWon will be set to false. So we're setting up a brand new game, and this will be called every time the user presses the New Game! button, which could be a lot if they play multiple games. Then we saw earlier how to create the deck, and also earlier in this course we saw how to set up the dealer cards, it's an array where we call getNextCard, twice. And we set up playerCards the same way, so both the dealer and the player start off with two cards each. Next we hide our newGameButton and we show our hit and stay buttons. and lastly we call showStatus, which we'll see in a second. Here's our createDeck function, this is exactly the same as it was created earlier in the course, and getCardString, that stays the same. And here's a new function that I've referenced before, it's called showStatus. And the purpose of showStatus is to set up our paragraph. Looking at this if statement, there's a new symbol here, it's an exclamation point and it means not. So if the game is not started we want to execute this code. We also could have said if gameStarted triple equals false, then execute this code, but generally you'll more likely see this not symbol. So if the game is not started we want to set the innerText of the textArea to Welcome to Blackjack! and return. And that's what we see right here. So now we're all set up. One of the first things we're going to need to do is shuffle our deck of cards, and we'll see that in the next video.
Let's take a look at how we can shuffle cards. I already made the changes, so let's take a look. Here's where we created our deck and added a new function call right after that. We call shuffleDeck passing it the deck. If we scroll down we can see that function, it's right here. So we create a for loop and we loop through every card in the deck. And the first thing we do is we calculate an index of a card that we can swap with. For example, we want to take the first card in the deck and swap it with some other random card, and we want to go through the whole deck this way. So we create a variable called swapIdx, and we call Math.random, multiplying it by deck.length. And we know that deck.length at the beginning is going to be 52 for the 52 cards, so we'll get a random number between 0 and 51, but it is a decimal value, so we need to truncate it, that's why we call Math.trunc. So we want to swap deck subscript i with deck subscript swapIdx. So we'll temporarily hold onto deck swapIdx. And then deck swapIdx, we'll set that to deck i. And then we'll set deck i to our tmp variable. So basically what we're doing is we're swapping deck i with deck swapIdx. And we do that for the entire deck and that's how we shuffle it. Now to prove that it shuffled, if you look down a bit, well first of all we needed to add this function, getNextCard, so I added that in, that was created earlier in the course, but in our showStatus now we're going to loop through the entire deck and we're going to populate our textArea.innerText with string values of the entire deck. So let's hit the New Game! button and see this in action. And we get our shuffled deck. It's starting with the Three of Hearts. if we refresh this, and hit New Game!, everything shuffled, now it starts with the Three of Diamonds. If we refresh it again, it starts with the Eight of Hearts, so we are getting a shuffled deck. In the next video we'll add a function to calculate the score of each hand.
Calculating the Score
Let's see how we can calculate the score in the Blackjack game. So here's what we want to see in our game. I've already coded it and we can look at the output. But in our paragraph we want to show the cards that the dealer has, and the cards that the player has. And we'll also show the score underneath, just to make it easier for us. So the dealer is dealt the Three of Spades and the Six of Hearts, that's a score of 9, and the player has the Nine of Clubs and the Jack of Spades. Remember, a Ten, Jack, Queen, or King are all worth 10 points, so the score is 19. And all of this gets done in showStatus. So let's look at that code. We create a variable called dealerCardString. And this is string form of all the dealer's cards. We loop through the dealer cards, and for each card we append the string version of the card along with a new line character. That's how we get each card on its own line. And then we do the same with the playerCards, we create playerCardString exactly the same way. And I'm going to skip this function call to updateScores right here, we'll look at that in a second, but I'll scroll down a bit, and here's where we actually change our innerText for our textArea. We show Dealer has with a new line, our dealerCardString, and then we show score + dealerScore, + a few blank lines. So we get this whole area right here to print out. And then to that we add the playerScore, which is done the same way, Player has, playerCardString, and the playerScore. Now in addition to that I'm also checking for gameOver. If the game's over we want to print out a message who won. If the player won we'll show YOU WIN!, else that means the dealer won so it says DEALER WINS. And also if the game is over, we're still in this block if the game's over, we want to show the New Game! button and we want to hide the Hit! and Stay buttons. So this isn't going to execute yet, but I just wanted to put the code in here because we're going to need it very shortly. So the thing we haven't looked at yet is this updateScores function call, let's look at that. I'll scroll up a little bit, and here's updateScores right here. We set dealerScore equal to a function call, getScore, passing it the dealerCards. And we do the same with the playerScore, we call getScore passing it the playerCards. So let's take a look at this getScore function. GetScore is right here, let's take a look at it. First of all we're passing it an array of cards. And we initialize the score to 0, and looking ahead, we're going to be returning the score. So that's how we get the score out of this function. We also set a flag called hasAce, it's a Boolean value that we set to false. It's important to know if the player has an Ace or not because that might add 10 more points to the score. An Ace is usually worth 1 or 11 points. Next we'll loop through all the cards. As long as i is less than cardArray.length we'll execute this block of code. We'll take cardArray i and assign that to card, and the we'll call getCardNumericValue, and this is a new function that I'll show you in a second, but we pass it the card and we get back the value of that card, and we add that to score. So score will increment as each card is read. And if the card.value is an Ace then hasAce = true. And again, this for loop will loop through all the cards. Now before we return the score, we check if hasAce is true. And here's a new symbol, it means and, it's a way of checking two different conditions that both have to be true. So if hasAce is true and the score + 10 is less than or equal to 21, we want to increment the score by 10. Remember, an Ace can be worth 1 point or 10 points. When we call getCardNumericValue up here and it returns an Ace the value will be 1. So here's where we add 10, as long as we have a valid score, as long as score + 10 is less than or equal to 21. And then we return the score. So the last piece of this puzzle is this call to getCardNumericValue. We pass it a card and we get back the card's numeric value. If we scroll up, we see it right here. We pass it the card, and we have a big switch statement. For an Ace we return 1, for a Two and a Three, and a Four, we return 2, 3, and 4, and so on. But if the card.value is equal to 10, Jack, Queen, or King, that'll get caught by this default block right here, and will return 10. So getCardNumericValue returns the value of the card between 1 for an Ace and 10 for a 10, Jack, Queen, or King. And we could make this more complex because an Ace could be worth 1 or 11 points, but because this is a beginning course we'll leave it simple and just return an Ace as 1 point, and then later on we'll handle adding 10 if possible to the score. So let's hit Refresh and make sure this works. Again I'll hit New Game!, and the dealer has a Jack and a Five for a score of 15, that's good, and the player has a Ten and a Seven for a score of 17, and that's fine. Now probably with a 17 we would want to stay, but if we click the Stay button we haven't set that up yet. Likewise, if we wanted a new card we'd press the Hit! button, and that's not set up yet. So in the next video we'll set up these buttons and we'll get closer to playing an actual game.
Taking a Card or Staying
So if you remember, the purpose of Blackjack is to get 21 points, or as close to 21 points without going over. You want to get the user to take a card, which his called hit or hit me, or when the user is done taking cards they can hit the Stay button, which says I'm done taking cards and now it's the dealer's option to take cards or not. So let's see how we implement this. Here's our event listener that we already coded for the New Game! button, but if you look here you can see that I coded two more event handlers, one for the hitButton and one for the stayButton. Let's look at the hitButton first. When the player presses Hit! they want another card, so we'll call getNextCard and we'll push that onto playerCards. Now it's possible that the player with their new card went over 21 and lost the game, so we'll call a function called checkForEndOfGame, and we'll code this a little bit later. If we look now there's just a stub in here, it's right here. So checkForEndOfGame does nothing, and I put a comment in there with a TODO as a reminder that this is something we need to do, but for now it returns nothing. So after we check for end of game we show the status again, we update our text area, and that's the hitButton. Now the stayButton means that we're done taking cards and effectively the game is over, so we'll set gameOver = true. Now the dealer still has an option of taking cards, and we'll take care of it when we call checkForEndOfGame. Then again we need to show status, update our text area. So let's take a look at our game now, I'll hit New Game!, and the dealer has 15 points and we have 13 points. So let's hit the Hit! button. And we were dealt the King of Diamonds and our score is now 23, so we lost. But the game doesn't know that yet because we haven't coded checkForEndOfGame. We can take as many cards as we want, and get our score up to 38, but we'll fix that in the next video. Let's just refresh this and see if the Stay button works. We have 14 points, but I'll hit the Stay button to see what happens, and we get a message that says DEALER WINS. But that's not entirely accurate, because we haven't coded checkForEndOfGame yet. So let's do that in the next video.
Completing the Game
We started off this module by setting up our game, making sure our variables are okay, and we're working with the DOM. We saw how to shuffle the cards, we called Math.random, and multiplied it by 52 to get a random number between 0 and 51, but it was a decimal number so we had to truncate it to get an integer. Next we calculated the score, and we added event handlers to the Hit! or Stay buttons so that the user could take a card or stay, and the way we set up the handler was by calling the button.setEventListener function. And then we completed the game making sure it did operate successfully, and we also saw that there are some features that you can add to it on your own, things like looking for a tie or showing a special message if you're dealt Blackjack, 21 points. So that wraps up our Blackjack game and we'll wrap up the course in the next video.
Mark started in the developer world over 25 years ago. He began his career with a Bachelor of Science in Computer Science from St. Johns University. After spending 10 years on Wall Street working...
Released19 Jan 2018