What do you want to learn?
Leverged
jhuang@tampa.cgsinc.com
Skip to main content
Pluralsight uses cookies.Learn more about your privacy
JavaScript: Getting Started
by Mark Zamoyta
JavaScript is the popular programming language which powers web pages and web applications. If you are new to programming or just new to the language, this course will get you started coding in JavaScript.
Start CourseBookmarkAdd to Channel
Table of contents
Description
Transcript
Exercise files
Discussion
Recommended
Course Overview
Course Overview
Hello everyone, my name is Mark Zamoyta, and welcome to my course, JavaScript: Getting Started. I am a software consultant and developer in the Portland, Oregon area. JavaScript is one of the most popular programming languages. According to GitHub, JavaScript is the top programming language, and it's more than twice as popular as the runner-up, Python. Learning the JavaScript language is valuable for any developer. JavaScript is the language of the web supported by all major browsers, but tools exist to take JavaScript far beyond web pages. You can create native smartphone and tablet apps, desktop apps for Windows and Mac, and even server-side apps using JavaScript. In this course I'll cover JavaScript programming for those who are completely new to programming. This is also valuable for programmers who are just new to the JavaScript language. We'll learn the JavaScript features needed to get you started, and we'll build the card game Blackjack along the way as a sample project. By the end of this course you'll know the very basics of JavaScript and you'll be able to build simple programs for the web. No prior knowledge of programming is required for this course. I hope you'll join me on this journey in learning how to program with my Pluralsight course, JavaScript: Getting Started.
Introduction and Our First App
Introduction
Hello, and welcome to JavaScript: Getting Started. My name is Mark Zamoyta. JavaScript is the programming language of the web. It started out as a way to add small bits of functionality to a website, but now JavaScript has evolved into much more. JavaScript is used on the vast majority of websites and is supported by every major browser. The language has evolved to support the creation of business applications on the web. And with web connectivity built in, almost any kind of utility, security, or data application can be created using JavaScript. Games can be created with JavaScript as well. You way have heard or Unity, a popular game engine for 3D and 2D games. JavaScript is supported as a programming language for this engine. For large business applications JavaScript is popular and has been embraced by a scalable language called TypeScript. This language is a superset of JavaScript, so you'll need to understand JavaScript well in order to write large-scale business applications and other software using TypeScript. JavaScript is not just for applications which run in browsers on the web, you can also create native applications for smartphones and tablets using JavaScript. A popular technology for this is Apache Cordova. JavaScript can also be used to create full-fledged applications for the Mac and Windows Desktops, there's no need for a browser at all. A popular technology to accomplish this is Electron. Writing server-side code can also be accomplished in JavaScript. You can create web servers, web APIs, and other services using a technology called Node.js. So JavaScript is a multi-platform language. It will run on any modern web browser. It can be used to create native applications on smartphones and tablets, it can create desktop software for Mac and Windows computers, and it can be run on any back-end server as well. No matter where you want your application to run you can code it in JavaScript. In this course I'll teach you the very basics of how to develop software using JavaScript. In the next clip I'll show you how we can get up and running very quickly.
Learning JavaScript in Plunker
In this course we're going to learn JavaScript using a tool called Plunker. And Plunker is simply a website, but it has a unique URL, it's plnkr.co. And notice that it's not .com, and also notice that it has no www prefix. It's simply plnkr.co, and let's go there now. I'm here at the Plunker website and you can sign in with GitHub if you'd like, but I'm just going to click the Launch the Editor button. And this brings us to a working program. The first thing I'll do is I'll hit this icon here for Live Preview. And you can see for our preview it just shows the text Hello Plunker. This section on the left here shows the files which make up our project. We have an HTML file, that's the markup for the web page, and you can see the h1 tag here, which shows Hello Plunker. But the important thing about this HTML file is that it uses JavaScript. This script line right here is what pulls in script.js, and we see script.js right here as part of the project, I'll click on that. And here we have our JavaScript file. Now this first line is a comment, and we'll be learning about those, but I'll just delete that for now. But we're actually all ready to go and we start coding JavaScript right away. There are few things about the editor I want to show you though. We can click on the settings button right here, Editor Options. And you can change some of these options if you'd like, but the main one I'm interested in is Auto refresh. You don't want to have to hit the Run button after you modify your code, so you might want your program to run automatically as you're typing. So throughout most of this course I'll have this set to Auto refresh. And along with this goes the Run button right here to preview your web page. I'll click that and it goes to this Live Preview icon and we can see our output. And a project in Plunker is called a Plunk. You can name your Plunk right here in the Description and then hit the Save button. Throughout the course you'll see me hide this left panel by clicking on the Close button here, and that can always be opened back up easily. And also you can resize your preview area on the right. And sometimes in the course I'll have it all the way open, just to show more code. Throughout this course we're going to be building a Blackjack game, and you might want to work with the exercise files for this course. To work with them, simply create a new Plunk, I'll launch the editor here, and if the exercise files include an HTML file you can just copy and paste it here, into index.html. There'll also be a JavaScript file, so you can go to script.js, remove everything here, and you can copy and paste the new script here. I'll load up the game here so you can see what we're eventually going to be able to build by the end of this course. Here's the Blackjack game running in Live Preview. I'll hit the New Game button, and we can see what the dealer's been dealt, and we can see what we've been dealt . And the goal of Blackjack is to try to get 21 points to win, or at least get more points than the dealer without going over 21 points. But since we have 14 I'll click the Hit! button, which means we want another random card. And we got dealt the Queen of Diamonds and we lost the game. DEALER WINS, let's play again. So the dealer has 14 points and we were dealt 2 Kings, we have 20 points. We'll stay, which means we're done taking cards. And we win, so the dealer took the 9 of Clubs, and their score is 23, which is over 21, so we win. We'll be gradually building this game throughout the course. So we're all ready to get started. In our next video we'll write our first JavaScript program.
Hello World
Whether you're learning how to program for the first time or you're learning a new language, like we're learning JavaScript now, the traditional first program that gets created is called Hello World. So here we are in Plunker and I'm at the script.js file. And let's click in the editor to activate it, and we'll write our Hello World program. When we're programming, essentially what we're doing is we're giving the computer commands, we're telling JavaScript what we want to do. So we'll type console.log, and I'll explain what the console is in a minute, but log means to log out a message, and I'll create parentheses, and in that I'll put single quotes and the words Hello World, and I'll add a semicolon at the end of the line. Now you'll notice this button says Stop, so Live Preview is running, but where is this printing out Hello World? We need to open up the Console. This is different whether than on a Mac or on Windows, or which browser you're in, but I'm on Chrome, and I can go to the menu for the browser right here and go to More Tools, and I'll go to Developer Tools. You can see the shortcut is Opt+Cmd+I, and that's because I'm on a Mac. On Windows you can usually just press F12. But if you can't get a key combination to work you can just open it from the menu like this. So now that Developer Tools are open, and we want to make sure we go to the Console tab, which is open. And you can see the text Hello World. So our first JavaScript program worked. Now we can change this by adding an exclamation point after World. And about a second or two after I type that we can see it showing up in the Console, Hello World!. So any changes we make in the editor will execute within one or two seconds. And this is good, but could also be a little bit bad or strange in ways. What if we have some kind of error in our program, like let's say, I didn't fully type things out yet. You'll see an error show up, but as I finish the typing we'll get the message. So just don't get thrown off by errors showing up in the Console. Always look at the last thing that prints out in the console to know whether it was successful or not. And here we can see it was successful, showing Hello World!. Another thing you might want to do is move the Console. I'll go to the Developer Tools menu here and I'll click this button to dock it to the right of the browser. So now the Console shows up on the right side. And it's totally up to you where you'd like this to be positioned, and I'll just put it back on the bottom for now. We'll be learning all about JavaScript in this course, but to start with there are a few key things to know. First of all, JavaScript is case sensitive. If we typed capital L here for Log, you can see that we get an error. So no matter what you type, make sure the case is correct. Also, we're free to add blank lines, or spaces, or tabs, these are called whitespace, but we're free to add those wherever we'd like. So throughout this course you'll see how I use whitespace to make the code cleaner to read. For a program like this I would usually put it on the second line, just to move it away from the top so it stands out and is more readable. But just remember that you can use whitespace wherever you see fit. So we have our first program up and running. One of the most basic concepts in JavaScript, or any programming language, is the concept of a variable, and we'll learn all about that in the next course module.
JavaScript Beginnings
Introduction
Hi, this is Mark Zamoyta for Pluralsight. This module is titled JavaScript Basics, so we'll get into the fundamentals of programming in JavaScript. Every application needs to store information, and the way we do that in JavaScript, or most languages, is with variables. So we'll see what a variable is and how we create them. And when working with variables or just plain coding, we're undoubtedly going to run into errors, so we'll see how to read error messages and fix things up. Next we'll see how to work with strings, which are words or sentences, that type of thing, or numbers, and how we use variables to hold them. Next we'll look at simple operators, those are things like plus, minus, the multiplication symbol, division, basically any kind of math operator. And we'll look at how to add comments to our code. Comments get ignored by JavaScript and the complier, but they're very valuable for people who actually read your source code, so we'll see how to create comments. And finally we'll start building out our Blackjack application. We'll add some variables to it, and comments, and it won't do much, but we'll have a good start. So let's get started and find out what variables are all about.
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
It's very easy to make mistakes when we're coding. All you have to do is type one character wrong in a variable name and things won't work. So let's take a look at some of the common errors that you'll run into, and it doesn't matter if you're a new programmer or you've been doing it for a long time, it's important to hunt down these errors quickly and fix them quickly. Here's the Plunk we've been working with in the last video, and I'll just simplify it a bit, we'll keep productName equal to Hammer. And we'll print out the productName, we'll make sure that works, and we get Hammer. What if we made a mistake and we spelled productName wrong? We'll just take out the a here in Name. You'll see that we get an Uncaught reference error, productNme is not defined. And let me put the Console on the bottom, I just want to make the error message more clear. So you don't need to worry for now about this Uncaught message, but ReferenceError is the type of error that we're getting. It's trying to look up this symbol and it just doesn't know what it is. And it's very clear about what the error is, productNme is not defined. And then at, and it tells us the file, script.js, line 4, that's what the :4 stands for. And we can see line 4 right here, so they do match up. So that's one error that's very common that you can quickly fix. Another error that's common is forgetting to even initialize and create this variable name. What happens if we just take out this let statement all together and we log out productName? Well we get another ReferenceError, productName is not defined. So the way to fix that of course is to define it. Now there's one other error that doesn't really show up as an error. What if we say let productName to create the variable, and we forget to initialize it, we don't set productName to anything. Well we can see here that it prints out undefined. We don't get an error message, but we do get this unexpected value. So an important rule of thumb is to always initialize your variables before you use them. So let's initialize productName again. And everything's fine. Now there's one other tricky problem you might run into. What if we created a variable name, and let's call it class, and we'll log out class. Well we get a syntax error now. Unexpected token class. The token just refers to that symbol class that we're trying to use. And there are a few words that we cannot use as variable names. These words have other uses in JavaScript, and of course we haven't learned them yet, we're at the beginning of this course, but it is important to be able to look them up in case you run into trouble with them. I went on the internet and I searched for JavaScript reserved keywords. And there are hundreds of pages out there that list these keywords. And you can see we tried to use the word class, which is right here, and we can't use that, we can't use any of these words. So it's worth going through this and making sure that you never use one of these words as a variable name. But even if you did accidentally use one of these words, you can see that the syntax highlighting is off. Let is in purple, because it's a keyword and class is in purple because it's a keyword. So if we change this from class to className, we can see that it's no longer highlighted as purple and it does work by printing out My Class. So these are just some of the common errors you'll run into, and you can see that all of them can be fixed rather quickly. Now so far we've been working with strings, those are words or something similar to words that are surrounded in quotes, double quotes, or single quotes, but another popular thing we do as developers is work with numbers, and we'll see how to do that in the next video.
Strings and Numeric Variables
So far the type of data we've been working with has been words, and those are referred to as strings, and we've been surrounding them in double quotes or single quotes. But it's also extremely common to be working with numbers, so let's see the difference between strings and numbers. So let's see what sample strings and numbers look like. For strings we've been working with Hello World in double quotes. We could also put Hello World in single quotes, like we see here. So in this example, Don't Speak!, we have an apostrophe, and because an apostrophe is a single quote we're going to use double quotes around Don't Speak!. And here we have a string in single quotes again, Welcome to Blackjack, and here's another example that's in single quotes, but it has an apostrophe in it, 're for we're. And you can see that we can use a backslash to get this apostrophe to show up, even though it's in the middle of a string. Without that backslash we'd get an error because it would think the string was just capital W-e, and it wouldn't understand the rest of the line. And that's called escaping a character, in this case we're escaping the single quote. And looking at numbers you simply enter a number without quotes. And that's very important to keep in mind. If you put quotes around your number it's very likely you'll run into bugs, as we'll see soon. Another example of a number is by using a decimal, we can specify 0.42, that's a valid number. Or we can enter larger numbers, such as 52 million, or very small decimal numbers such as this. So let's go back to Plunker and let's work with strings and numbers and see the importance of why we don't use quotes around numbers. So here's our example code where we're simply printing out a variable name. And let's just see an example of using an apostrophe. I'll create a string that's in single quotes, and we'll call the productName John's Hammer. And we can see here that we get a very definite error, we get a syntax error because we're using a single quote within a single quoted string. So let's escape it. I'll enter the backslash before the single quote, and everything's good now. We log out John's Hammer. Now let's take a look at working with numbers. Let's create a variable called price, and we'll set it to 5.00, and we'll log out the price, and we get 5. So notice that price is being set to 5.00 without the quotes, and we can still log this out the same way as a string. If we created another variable, let's call it price2. And we can have numbers on variables names, it's just that the variable name cannot begin with a number, but we'll set price2 = 3.00, and we'll log out price, price2. And we get 5 and 3, as expected. It's chopping off the cents, the .00, but that's fine. Now one thing we can do with numbers is we add them together. So if we log out price + price2, you can see that we get 8. So we're doing addition by using the plus symbol, 5 + 3 = 8, and that's what we get. Now the big problem with this is, what if we put price2 in quotes? Well, math things are really messed up. It says 5 + 3 is 53, and that's very wrong. So when JavaScript sees a string it doesn't know that it's a number and it will convert everything to a string. So that's why we get 5 for price and then 3.00 for price2. And if you ever run into trouble with strange calculations like this, the first thing to check is to make sure that your numbers stay numbers. You don't want a number to ever be a string. So remove the double quotes, and it's back to running fine again, 5 + 3 = 8. Now this plus symbol has a very different meaning when you're working with strings. Let's create two new variables here. Let's create a variable called firstName, I'll set it to John, and we'll create another variable called lastName, and we'll set it to Doe. And let's print out firstName + lastName. And you can see we get JohnDoe, but it's all run together. So what this plus symbol does, when working with strings, is it just combines everything together. This is called concatenation, it combines firstName with lastName. So of course we want a space to appear between those two. So what we can say is firstName +, a string with a space in it, + lastName. And now we get John, space, Doe, which is probably what we wanted to print in the first place. So this plus symbol has two very different meanings. If it's used with strings it just runs the strings together, it's called concatenation, and if it's used with numbers it will do addition. And like we saw, the thing to watch out for is make sure that your numbers stay numbers and not strings. Never use quotes with a numeric value.
Simple Operators
When we're working with numbers you're very often going to be using operators. And let's see what the common operators are. So we use the plus sign for addition, we just saw that in the last video, and we use the minus sign for subtraction. For multiplication we do not use an x, we use an asterisk, which is usually located over the number 8 on the keyboard. And for division it's very hard to type a division sign on a normal keyboard so we use a forward slash for division. And another common operation is to get the remainder of a division, and we use the percent symbol for that. Some computer languages call this the modulus operator, but in JavaScript it just gives us a simple remainder. And just like in all math we can use parentheses. So let's see these operators in action. So here's the Plunker I set up, it has two variables. First set to 12 and second set to 3. And of course these are not in quotes, we're going to be working with numbers here. And when we log out first, second we get 12 and 3. Now one thing that's common to do with numbers is to do the calculation before we print out the number or use it in some other way. So let's create a new variable called answer. And we'll set the answer equal to first + second, and then let's log out this answer. And we get 15, that's correct, 12 plus 3 is 15. Now let's change the code to first - second. And we get 9, which is correct, 12 minus 3 is 9. And let's do multiplication with the asterisk, 12 times 3 is 36, so that's correct. And then for division we use the forward slash. First / second, 12 divided by 3 is 4. Now let's change the second number to 5, and we'll get the remainder. So first % second is 2, because 12 divided by 5 is 2, but it also has a remainder of 2. If we change this number to 6, we can see the remainder is 0, that's correct. Now one of the important things to remember in working with any mathematics, not just on the computer, is the use of parentheses. Let's do away with our first and second variables for a second and we'll set answer = 3 + 4 * 5. Now at first glance you might think that the answer would be 3 plus 4 is 7, 7 times 5 is 35, but that's not the case, the answer is 23. We can see it here. So what's happening? Well multiplication and division always get performed before addition and subtraction, so it executes 4 times 5 first, which is 20, and then it'll calculate 3 plus 20 is 23, and that's how we get the answer here. And this is another very common source of bugs. If what we meant to do is execute 3 plus 4 first, we would need to put those in parentheses. So now we look at the answer and we get 3 plus 4 is 7, we do that first because of the parentheses, times 5 is 35, and that's what we get for an answer. So two things to remember when your calculations don't seem to be performing properly, first of all, make sure that your parentheses are in the right place if you need them, and secondly, make sure that your numbers are never strings, never surround a number in quotes. Now one other thing I want to show here, is that these operators can be used anywhere. Like we might want to just initialize answer here to 5, but then later on in the code we might want to change answer. Let's say answer = 8. Now we don't have to redeclare the variable, it's already declared, so we don't need the let statement to use this variable anymore, we can take the number 8 and assign it to answer with the equal sign. And you can see that the output is 8. So the variable answer starts out as 5, but as the code executes answer becomes 8 and that's what shows. Likewise if we reset answer again, it logs out 12. So those are all the common operators that we're going to run into. And that's all we're going to look at as far as variables go for this course module, but we'll be using them in more detail throughout this entire course. In the next video we're going to take a look at commenting our code, and we'll see why that's important.
Commenting Code
It's very important to be able to comment to your code so that you can give notes and information to any future developers that look at your code. So let's see how we do that. So here we have a JavaScript file and the first line is a comment, it uses two forward slash symbols, //, and it says this is a comment. And you can put any text there you like, JavaScript is just going to ignore it. The first thing that JavaScript will really see and execute is the let statement. Let's look at another example. Here we have empty lines with comments, and that's fine too. You'll see this a lot because it's a way to make the comments stand out from the source code. It just adds a little bit of space around it and a little bit of formatting. But just because you use a // doesn't mean you need to enter anything after it, it can be a blank line such as these, nothing necessarily needs to follow it. And here's another type of comment, instead of using // you can use one /* symbol at the beginning of the comment and another */ symbol at the end of the comment. And anything between these two symbols will be a comment. JavaScript will ignore it. And comments don't need to be on their own lines as we've seen. If we wanted to comment a single line of code, sometimes you might want to put that comment directly on that line of code. Just remember that after the // everything following that symbol will be the comment and will be ignored by JavaScript. So let's go to Plunker and create some of these comments. Here we have a simple Plunker, similar to what we did in the last video, and let's add some comments to it. I'll add the comments on top. So these three lines that begin with the double slash, these are all comments, and they'll be completely ignored by the JavaScript compiler. These comments are meant for humans to read. And another way we could have done this is with the /* syntax. So enter /* to start the comment, and then to end the comment I enter */. Anything between these two symbols are now a comment. We can go ahead and add as much white space and other text as we'd like. Some of the things we could add in a header such as this would be a copyright notice, a license for the source code, or just any kind of information that someone would need to know about this file. Now if we wanted to we could comment a single line of code. Typically that's done with a double slash towards the end of the line. So if this were a scientific application you might want to leave a note on why we are setting answer to 32, it's the freezing point. And again, JavaScript is going to ignore this comment. One other common use for our comment is to comment out your own source code. Sometimes you might want to take a step backward, make sure things are working properly, and let's do that with line 10 here. Let's say we want to ignore this calculation, just temporarily. I'll comment out this line, and now we can see the answer is 32. And as we work on our source code and everything's working fine, we might want to add this calculation back in. So I'll delete the comment, and we get the answer 42 again. So those are the main reasons for using comments. In the next video we'll start to build our Blackjack application. We know about variables and comments so we'll add those to form the basis of our game.
Starting Our Blackjack Application
So let's start building our Blackjack application. We can't it to execute much, but we can start to work with variables and comments. So I'm here at Plunker, and if you wanted to you can go ahead and create a new Plunk. And you can save that off, if you'd like. I'm going to go to the script.js file, and this is where we'll start coding. Let's start off with some comments. I'll just put the app name, by Mark Zamoyta, my name. And of course you could put a copyright notice in there, or some kind of license, just anything you'd like because JavaScript is going to ignore it, it's meant for developers to look at. So to start playing Blackjack let's create some variables, and what kind of variable would we need when playing Blackjack? Well you're going to be dealt two cards, so let's create some card variables. And we'll call them card1 and card2 for now. Card1 will be the Ace of Spades and we'll set card2 equal to the Ten of Hearts. And we'll print them out with a special message. First we'll say Welcome to Blackjack!, and we'll say console.log, You are dealt:, and we'll just put some spaces in there to indent a little bit, and we'll specify card1, and we'll specify space again, + card2. And I'll put the console on the bottom so it looks clear. And we get Welcome to Blackjack! You are dealt: Ace of Spades and Ten of Hearts. So it's not much of a game yet, but it's a great start. We have some variables set up and we're showing some output. Throughout this course we'll be building up this application so that it really works, but feel free to modify this as you like. Maybe you want to add the number of chips the player has, maybe you want to enter a variable for the minimum bet that the player can make, go ahead and create variables and experiment. The best way to learn is by making lots and lots of variables, maybe even performing some calculations, and hopefully if you run into any errors you'll know how to fix them. So let's wrap up this module with a summary.
Summary
So we've learned the very basics of JavaScript. We looked at variables and how we can store information in them. Specifically we looked at storing strings or numbers. You declare a variable with the let keyword. And we always want to initialize a variable before we use it, otherwise it gets set to that undefined value, which we most likely don't want. We looked at handling variable errors and some of the common scenarios that come up when we have a typo or when we forget to declare or initialize a variable. We looked at string and numeric variable types, and we saw how the plus symbol is used for concatenation for strings and it's used for addition for numbers. Next we looked at some of these simple mathematical operators. These include plus, minus, division, which is the forward slash, multiplication, which is the asterisk, and our remainder operator, which gives us the remainder of a division. Then we looked at comments. We saw how to comment our code with two forward slashes, or a /*, */ combination. Finally we created our Blackjack application, or the very beginnings of it, but we put variables and comments to use, and we'll be ready to build upon this in the rest of this course. So now that we know a bit about variables, in the next module we're going to learn a bit more. We've looked at strings and numbers, but there are also other types of variables that we can work with. Also, a variable holds only a single value, but in a lot of cases we're going to need to hold multiple values. For example, a deck of cards is 52 different values for the 52 different cards. And we'll see how we can use arrays in JavaScript to deal with that, and that's coming up in the next module.
Types and Arrays
Introduction
Welcome to this module titled Types and Arrays. My name is Mark Zamoyta. By types we're referring to the information that's stored in a variable, not its value, but what type of value it is. Is it a string, a number, or something else? And an array is a mechanism that lets us hold more than one value. We could store a whole deck of cards, a huge list of every person in the city, or any another information that's more than just one value. We'll start off this module by looking at string and number types. We've already worked with these a bit, but there's a little more information you need to know about them. Next we'll look at Boolean types, and those refer to variables that are either true or false. And there are two special values that we need to be aware of when working with JavaScript. One is undefined and the other is null. We'll see how to use these and what the major difference is. And next we'll look at arrays for storing multiple values. We can store multiple strings, multiple numbers, or a large collection of just about anything. And then we'll look at some of the key features you need to know when working with arrays. How to add new values into an array, how to insert values, how to pull values out of arrays, and that kind of thing. And we'll wrap up this module by adding arrays to our Blackjack game. So let's get started and look at string and number types.
Type Basics: Strings and Numbers
In this video we'll take a look at types, and by types we mean the type of data that we're working with. And the two types that we've seen so far in this course are strings, those are values in quotes, and numbers. So let's go straight to Plunker and start working with some examples. Let's create a simple string. We'll use the let keyword, we'll call the variable value, and we'll set it to a string, I'll say apple. And of course we can log this out. I'll specify a value, the variable name, and I'll make sure I have Live Preview on, and we get apple. Value is of type string, but how can we tell that? One easy way to tell is with a built-in function. I know we haven't learned functions yet, but for now we can type typeof, all in lowercase, and we'll surround value in parentheses. So we're executing typeof value. And the result we get is string. So that tells us that the type of value is string. Now what if we had value be a number, such as 99? Typeof value is now number. So not only is the value of a variable important, also the type is also very important. And it's especially important when working with numbers to make sure that your number is a number type. We saw this in the last module, but I'll show it again just because it's extremely important. What if we let value be equal to 9 in double quotes so that it's a string? And what if we logged out value + value. You would expect 9 plus 9 to be 18, but instead we get 99. And that's why you always want to have your numbers be real number types. We can get the answer we expect by taking out the double quotes. Now 9 plus 9 is 18. So those are the important differences between string and number types, but I want to look at numbers in a little bit more detail, because numbers have a few quirks in JavaScript. Let's take a look at value and I'll set value = 4.1 + 4.3. And you would expect that the answer would be 8.4, but if we look at the result we got, we got 8.39999 and so on. And this is an inaccurate answer. It's very close to the right answer, and it might be acceptable in certain circumstances, but it's not what we expect. And this just happens to be a quirk with the way JavaScript handles decimals. We'll see later in this course, in the module on objects, how we can use a math object to round this number, and get it to be what we expect. But for now, as you're working with numbers, and experimenting, just be aware that you might get some of these very tiny inaccuracies. Another quirk with numbers that you might run into is what is 10 / 0? Well we know that that's impossible in math, you can't really divide by 0, but look what JavaScript gives us. It gives us an answer of Infinity. Also, what if we did a -10/0? We get an answer of -Infinity. So this a very unique feature of JavaScript that it works with these strange values. Most other programming languages would throw an error if you divided by 0, but I just want you to be aware of this in case you run into it. We're not going to go into too much detail on how to work with these infinity values. And another quirk that JavaScript is famous for, is what if we calculated 0/0? We get a strange symbol called NaN. And that stands for Not a Number, and this is a value that could come up once in a while, and you should be aware of it. And there's a very strange quirk that goes along with this. What if we specify typeof value? We get a number. So the value itself, let me print that out first, so I'll print out value and then typeof value, we get Not a Number, but it's of a type number. So as you're experimenting with your own code, and your own calculations, and numeric values, just be aware of things like infinity, and this Not a Number symbol, and the quirk that typeof Not a Number is actually a number. So that covers two of the popular types in JavaScript, strings and numbers, and in the next video we'll take a look at Boolean values, we'll see what those are.
Boolean Types
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
There are two more types that are very important in JavaScript, and they're pretty simple to understand. One is undefined and the other is null. Let's see how these are used. So if we compare undefined and null, for undefined JavaScript will initialize variables to undefined. So if we declare a variable with the let statement, but we don't use the equal sign to assign it a value, the value of that variable will be undefined. And it's a general rule of thumb that as developers we don't assign undefined to variables, we let the JavaScript engine do that. But if we did want to blank out a variable, the convention is use what's called null. Null is a different value from undefined, but in a similar way it means nothing. But our source code should set variables to null if needed. So we wouldn't blank out a variable by setting it to undefined, we would blank out that variable by setting it to null. And that's just a convention that's been developed to give a developer a clue as to what's going on with the code. Was this variable never initialized? Or did a developer specifically set it to null? We can tell with these two different values. Let's see some examples. So I'm in the Plunker from the last video and let's just set calculateSalesTax to nothing. We'll declare it, but we won't initialize it. And let's log it out. We get undefined. Now if we had some more complex code here and somewhere along the line we wanted to blank out this variable we wouldn't set it to undefined again, we would set it to null. And that way when it logs out we get null instead of undefined. And we can look at the types of these variables as well. Let me comment out this line and we'll set calculateSalesTax to undefined, but let's also print out its type. I'll specify typeof and the variable name. We get undefined and then the string undefined. So undefined is its own value, but it's also its own type. And what if we set calculateSalesTax to null? I'll uncomment this line. Its value is null, but its type is object. And we'll learn about objects later in this course, but at this point in time when you're beginning to code in JavaScript, the fact that null is an object isn't too important, we're more concerned with the value of null itself. So to sum things up, if we have an uninitialized variable, such as this one, the JavaScript engine initializes it to undefined, but if we wanted to blank out that variable itself we assign null to it, as we see here. So that covers all the main datatypes we're going to be looking at for now, strings, numbers, Booleans, undefined, and the null value, which is a type of object that we'll learn about later in the course. In the next video we'll learn how to store multiple values in a single variable, we do that with arrays. So instead of creating 52 variables for the 52 cards in a deck of cards, we can simply create one array, and we'll see how to work with this in the next video.
Storing Multiple Values in Arrays
Let's say you had a video collection of 2,000 videos, the last thing you want to do is create 2,000 variables to store the names of those videos. In JavaScript we can store multiple values in arrays. Let's see what they are and how we can create them and work with them. So this is how we create an array, we use the let keyword and we give it our variable name, in this case the variable name is values, and we assign it square brackets. The square brackets are located usually to the right side of the p character on your keyboard. You don't want to confuse these with the curly braces or parentheses. Arrays specifically work with square brackets. So in this example, values will be an array, but there are no values in it yet, let's see how we do that. So here we're going to initialize an array. We let values =, we have our square brackets, but in between the brackets have 1, 2, 3. So these are the three numbers that are being stored in this values array. So once we have an array set up how do we access the information within the array? So we let values equal the array of 1, 2, 3. And the way we access these values now is through a mechanism called subscripting. We take the variable values and we use square brackets directly after it, and we give it the index of the number we want to look at. So in this case we're looking at values, index, 0. And 0 refers to the first element, which is 1. And you can see the comment that I put here, that just shows you the answer, like what will log out in the Console. So values subscript 0 is 1. Looking at the next line, values subscript 1 would be right here. That's the value 2. And the next line, values subscript 2 would be this number here, 3. And what if we tried to reach a value that doesn't exist? If we look at values subscript 3 we'll get undefined because nothing exists at index 3. Now if this seems a little bit confusing, that value 0 would equal 1, that actually is confusing when you start working with arrays as a developer because the first element in an array is index 0. And this is the source of countless bugs that you'll run into. If there's anything worth remembering it's that arrays are indexed starting at 0. So this is index 0, this is index 1, this is index 2, and index 3 and above don't exist, you'll get undefined. Now we're working with numbers here, but we could also work with any datatype in an array. Here we have some examples with strings. We'll let cards equal an array of Ace, King, Queen, and Jack. So cards 0 is Ace. Again, remember that the first item in an array is indexed at 0. Cards 1 is King, cards 2 is Queen, and cards 3 is Jack. Anything after index 3 is undefined. So cards 4 and above are all undefined. So now that we've seen how to create arrays, and initialize them, and look at some of the values, let's go to Plunker and see this in action. I'll start off with a blank Plunk and let's create an array. So I'll initialize cities equal to an empty array. There's nothing between the square brackets yet, and let's log out cities. And you can see that we get an empty array. Let's initialize cities with some values. I'll enter New York, Los Angeles, and Chicago. So if we look at the Console we get this value 3 in parentheses, and that just tells us in the Console that there are three elements in this array. And that is the proper term to use when talking about the items within an array, it's elements. So the cities array has three elements, New York, Los Angeles, and Chicago. Now let me add some space here, just so we can see the subscripts better, but let's access cities 0. And we get New York. And again, one of the common bugs that new developers run into all the time is they would want to access new York and they would say, that's the first element in the array, so let's access cities 1, but that would give us Los Angeles, New York is at cities subscript 0 and Los Angeles is at subscript 1. And of course Chicago, it's the third city mentioned, but the subscript for it is 2. So we get Chicago. And again, we could use any values in this array. Let's go ahead and use some numbers instead. I'll use the number 0, 1, and 2. And that'll make it easy because now cities 0 will equal 0 right here. And likewise cities 1 will equal 1, and cities 2 will equal 2. One thing you could do with arrays is mix up the type of data that you're working with. You could put some strings and some numeric values in there, but that tends to be confusing. You want your array to all have the same datatype, it's not a requirement, but it makes things a lot cleaner if the developer knows that the array is filled with all strings, all numbers, all Boolean values, or what have you. So these are the fundamentals of how to create arrays, initialize them, and look up their values. In the next video we'll take a look at some more operations we can perform on arrays.
Array Features
There are many different things we can do to arrays to manipulate them, to add new elements, to delete elements, to modify elements, so let's take a look at some of the key features that we use often. So I have a Plunk, we'll let values equal an array of 0, 1, 2, and we'll log out values. We get 0, 1, and 2. One of the most important things we usually need to know about arrays is how many values are stored in them. And we do that by adding a .length to values. So we specify values.length. And we see we get a 3. If we added another element here, we can see that values.length is now equal to 4. If we're working with an empty array, values.length is 0. Let's look at how we can add new values. We initialize values to an empty array, but then we can specify values.push, and in parentheses we can specify a value to push. Let's push 44. And we'll log our values as an array. And we get the array with the 1 element, 44. Let's push some more values, 33 and -100. You can see that it adds the values to the end. We get 44, 33, and -100. And if we wanted to access that -100 we can specify values 2. We get our -100 because 2 is the index of -100 right here, 44 is index 0, 33 is index 1, and -100 is index 2. And let's look at removing an array element. Let's say we have the values 1, 2, and 3, and I'll log our values. Let's execute values.pop. And we see that values is now equal to just 1 and 2, it popped off the last value, it removed it. And when it removes that value we can store it in a variable if we'd like. Let's let result = values.pop. And let's log out result. We get 3. So again, values.pop removes the last element. If we add another element, 44, that will get popped out of the array, the result is 44. And instead of removing the last item, what if we wanted to remove the first item, this 1? We can call values.shift. And now we get the value 1. You can think of shifting as removing the first value and moving everything else down one index. So if we show result and also the new resulted values, we know the result is 1 right here, but our new array contains the elements 2, 3, and 44. And how would we delete an element? Let's remove result for a second here, and I'll remove it from the log statement. Let's call values.splice. And the first number will be the index we want to delete. Let's say we wanted to delete this 44. That's index number 3. So we'll specify a 3 here, and we want to delete just one value, so I'll enter a 1. When we look at values the new array contains the elements 1, 2, and 3. What if we specified index 0 and we delete 1 value? The new array contains 2, 3, and 44. Again 0 specifies the first element, which is 1, and this 1 here specifies how many items we want to delete. What if want to delete 3 items? Well we deleted the 1, 2, and 3, and we're left with 44. Splice also gives us the ability to insert items after the delete. So we'll delete 1, 2, and 3 again, but then we'll insert 11, 22, and 33. And our new array contains 11, 22, 33, and 44. So these are some of the key operations that we perform on arrays. You have push, pop, shift, splice, and there are actually a lot more. Let's look on Google and see if we can find a list of all the available operations. And I'll search for JavaScript array methods, and I'll click on this first link here for W3Schools, and if we scroll down a bit we can see array methods. And we'll learn about methods later in this course, but these are basically the actions that we can execute on arrays. If we scroll down we can see push and pop like we learned, shift, and here's splice. And to experiment you can go ahead and look through this entire list and see if there's something useful to you. By the end of this course a lot of these methods will make a lot more sense. So if they don't make sense right away you should go ahead and watch the modules on objects and functions and you'll be able to work with these a lot better. So that's all we cover on arrays for right now. So the next video let's add some arrays to our Blackjack application.
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.
Summary
We started off this module by looking at string, number, and Boolean types. We saw how Boolean types are true and false, and we saw some of the quirks that had to do with number types. Then we looked at the undefined value and the null value. We saw how variables are initialized to undefined by the JavaScript engine itself, but if we ever wanted to clear out a variable as a developer, generally the rule thumb is to set the variable to null. Next we looked at arrays, how to create arrays and initialize them, and using the square brackets to create them, but also to access the array elements. Elements is the term that we used for the items stored in the array. Here's a statement where we let arr, a variable name for array, equal the array with values 1, 2, and 3. And we saw how to index these values and access them. We put the index in square brackets, and always remember that the index is 0-based, so to access the 1 in this array its index is actually 0, and the value 3 in the array has an index of 2. Next we looked at some features of the array. We saw how to access the length of the array, we saw how to push values into the array and pop values off of the array, and we use shift to get the first item of the array and pull that out, and we use splice to delete array elements and even add new elements in the deleted item's place. Then we wrapped up this module by adding some arrays to our Blackjack game. So we actually know a lot now about variables and the types of data that the variables hold. And working with data is okay, but programming really gets fun when we start working with loops and conditional statements, and we see what those are all about in the next course module, so I'll see you there.
Program Flow
Introduction
This module is titled Program Flow. My name is Mark Zamoyta, for Pluralsight. The flow of our program is simply from top to bottom. JavaScript will start at the beginning and start executing lines one by one, and that's what we've seen so far in the course. But there are ways to conditionally execute code. There are also ways to execute the same code over, and over, and over for repetitive tasks. Let's take a look at what we'll be covering in this module. Sometimes we want to include or leave out a whole block of code and we can do that by using an if statement. We'll see how to set up a condition so that code can be included or excluded. An if statement can also have an else block. So if our condition is true some code will execute, else other code will execute. We'll also look at switch and case. This is another way to conditionally execute code. Next we'll get into looping. Looping refers to executing the same code over and over. And this is great for creating a deck of cards, looping through all the cities on a map, or taking any kind of array and processing each item one by one. And there's another type of loop called a while loop, and we'll see how to work with that as well. Now there is one big warning when working with loops. Sometimes you can get into a condition where the loop never exits, and that can hang up your browser window. Or if you're working in another development environment it can cause trouble. So let's quickly look at Plunker and make sure we have automatic refresh turned off. I'm at Plunker, and if you look at the menu on the right side, you can see Editor Options. There's an Auto refresh flag right here, and just make sure that that's turned off. If we go back to the Live Preview button we can make sure it's stopped before we start coding. And that'll just help us when we're creating loops to make sure that code doesn't execute and to help us make sure we don't get caught in one of these infinite loops that never ends. So we'll start off this module by looking at an if statement.
Conditionals Using if()
So far all of the flow in our programs have been from the top to the bottom of the source file. JavaScript will just execute each line one by one, skipping any blank lines. But there are times where we may need to conditionally execute some code, and we use the if statement for that. Let me show you some examples. So here we have an if statement, we use the if keyword, and then we use parentheses to put an expression. Here the expression is 5 is equal to 5. And we use the triple equal sign to compare numbers or values. And because we're working with a condition the answer is going to be either true or false. So is 5 equal to 5? That's true. And because it's true this code will execute. Notice the curly braces here. This is called a code block. So if 5 is equal to 5, anything within these curly braces executes. Here we only have one line of code, but you could have several lines of code here. So in this case, the word yes does print out to the Console. Let's look at our next if statement. If 5 is greater than 10 you want to log out the word No. Is 5 greater than 10? No it's not. So this block of code will never execute. And let's take a look at the third if statement. If 5 is greater than or equal to 5 we want to log out yes. Is 5 greater than or equal to 5? That's true, so it will print out Yes. So when comparing values we have the triple equal sign to see if they're equal, we have greater than, or you can use lesser than, it's not shown here, or you can have greater than or equal to, or less than or equal to. Let's look at a more realistic example that uses variables. Here we're letting the variable state equal FL for Florida. And we're letting the taxPercent variable equal 0. And then we have our if statement. If state is equal to FL we want the taxPercent to be 7, and then we log out the taxPercent. So let's look at this condition here. Is state equal to FL? Yes it is. So taxPercent will get set to 7, and that will print out in the Console. Let's look at a slightly different version of this now. So again, we're setting the state to FL, but we're setting the taxPercent to 7. And if we look at our condition now, the condition is exclamation point, which means not. So this symbol here means not equal to. If state is not equal to FL then we're going to execute this code, which sets the taxPercent to 0. And we log out the taxPercent and the taxPercent is 7. So looking at this condition, state is not equal to FL, that's false, state is equal to FL. So this code never executes. Now when it comes to these conditions the condition is going to evaluate to be the value true or the value false, and let's see what those values mean in JavaScript. JavaScript developers use the words truthy and falsy to describe whether a condition is true or false. And let's look at some of the falsy values first. Obviously the Boolean false is a falsy value. And 0 is a falsy value. If you have a pair of double quotes with nothing between them or a pair of single quotes with nothing between them, those are called empty strings. They're strings with nothing inside them, and those are false. The value null is false, the value undefined is false, and the value NaN for Not a Number is false. So if those are all false, what is true? What could you consider truthy? Well the basic definition of truthy is everything that's not falsy. So let's see some examples. True is obviously truthy, any number besides 0, such as 0.5 is truthy, even the number 0 is quotes is truthy. That might seem odd, but remember it's a string, it's not a number. And if there's any character in that string, it's truthy. So now that we've seen the if statement and some examples of things being truthy or falsy, let's go to Plunker and work with some if statements. So I'm all set up here, and let's let score = 1000, and then we'll just simply log our Score is score. So we get Score is 1000 in the Console. Now let's add an if statement to this. We'll write if and parentheses, and then we'll create our code block. So if our condition is true we'll execute this code block. And let's say if score is greater than or equal to 1000 we'll execute the code block. So if this is the case we'll increment score as a bonus. Score = score + 100. So looking at our if statement again, if score is greater than or equal to 1000, we'll take score and add 100 to it, so that would be 1100, and then we'll assign that back to score. So it is possible to have a variable on the right side of the equal sign and then have that variable be reassigned, as we see here. So score + 100 would be 1100, and that'll get placed in the score variable. And we see in the Console, Score is: 1100. What if we changed our condition to score is greater than 1000? Now this condition is false and score will not be incremented by 100. We look in the Console and Score is: 1000, that's correct. What is we placed score triple equal sign 1000? Well that's true, so now score is 1100 again. And what if we specified score is not == to 1000? That evaluates to false, so the score is back to 1000. And you can go ahead and experiment with all these different comparisons. You have the triple equals, the not ==, like we see here, you have greater than, less than, greater than or equal to, and less than and equal to. In the next video we'll work with if statements a little bit more, but we'll see how we can execute code if the conditional turns out to be false.
if … else
We just saw the if statement, but we can add an else keyword to it to execute another code block in case the condition is false. So here we have a similar example to the last video, we're setting state to FL, but we're not initializing taxPercent. And then if state is equal to FL we'll set the taxPercent to 7, that's the true condition. But then we specify the else keyword and a new code block. This will execute if the if statement is false. So if the state is not FL, we set the taxPercent to 0. When we log out taxPercent we get 7, because state is initialized to FL. And here's another example where we're going to chain if statement with the else. We set state to FL, we set taxPercent to 0. If the state is equal to FL we set the taxPercent to 7, else, and then we have a new if statement, if the state is equal to NY we set the taxPercent to 8.875. But in this case the state is FL so we log out 7. If we initialize state to NY we'd get a taxPercent of 8.875, and if we initialize state to Texas or some other state, our taxPercent would be 0. So let's take a look at this in Plunker. Let's modify our code from the last video. If score is greater than 1000, we'll give the bonus. Let's add our else keyword and a new block. And if the score is less than or equal to 1000, let's log out No bonus!. We look in the Console and we see that No bonus! does print out. Because score is equal to 1000, this block won't execute, however, our else block will. So now let's say else if, we'll add a new if statement here, if score equals 1000 let's say Almost!. So this is false, this won't execute, but score is equal to 1000, so we do print out Almost!. And let me clear the Console and let's just change the score to 100, see what happens. It simply prints out the score is 100. Score is not greater than 1000, so this won't execute, else if score is equal to 1000, that's not true either, so that won't execute. What we could do is add another else statement. And I'll add a code block and I'll say, console.log, Nice try!. And you can see that we get Nice try! Score is: 100. So this block of code will only execute if all the if statements above it are false. And one thing to remember is the use of whitespace in JavaScript. Sometimes you'll see else placed on the same line, such as this, or sometimes you'll see the next if statement below. And this could be confusing, but it ends up with the same result. I like to style it like this, where each else is on its own line along with an if statement or along with the beginning of a block. Another thing you might see in other developer's code is if your block of code, right here, has only one statement in it, you can leave off the curly braces. So let's just do that and see that we get the same result. This block has only one statement so I'll take out he braces here as well. And this block has one statement too, so I'll take out these braces. And you can see that it still runs fine, Nice try! Score is: 100. But it's the best practice to always include the curly braces, it makes the code a lot clearer and it helps prevent bugs in the future. If you compare this to all the braces back in, I'll hit Ctrl+Z to put them all back in, it just makes it more clear, and if a developer adds more code in the future the curly braces are already there.
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()
There's another type of popular loop in JavaScript called a while loop. Let's look at that one. Here we have a while loop. We'll declare count and initialize it to 1. Then we specify the while keyword, and in parentheses we put a condition. As long as this condition is true the code block will execute. So while count is less than 5, these two lines run. The important thing to remember in a while loop or any loop is that we need a way to exit. Here we're adding 1 to count with count++ And that way we're guaranteed that count will eventually become 5 and the condition will fail. But if we left this line out we'd get an infinite loop and that could hang up the browser, or whatever environment we're running in. That's not good. So let's go ahead to Plunker and create a while loop. So in Plunker the first thing I want to do is go to the Editor Options and make sure Auto refresh is turned off. That'll help us prevent an infinite loop. And I'll go back to Live Preview and I'll just make sure that we're stopped. So let's write our code. We'll let count = 1. And I'll enter the while keyword, and in parentheses we put our condition. Count is less than 3. And here's the code block that we'll execute while count is less than 3. I'll log out count and it's important to remember to get out of this loop and we do that by incrementing count. Let's run it. I'll open up the Console and you can see we get the values 1 and 2. Count started at 1 and while it was less than 3 we printed it out, so we get 1 and 2. If we started count at 0, and said count is less than or equal to 3, I'll run this now. We get 0, 1, 2, and 3. We started at 0 and while count was less than or equal to 3 we ran the loop. So while loops are pretty straightforward, they're a little bit simpler than for loops, but you can pick the right looping technique for whatever it is you're coding. Let's just take out this count++, just to see what happens if we accidentally create an infinite loop. So I'll stop the program and run it again. And you can see that we get 0 printing out and it's increasing like crazy, it's just goes up, and up, and up. This value is how many times the number 0 is showing, and it's going to show forever. If I click in the Editor it's not responsive. If I try to x out of the tab, that doesn't work at all. So we're stuck. We can get out of this in Chrome on a Mac, possibly in Windows too, by going to the Menu, selecting More Tools, and going to the Task Manager. In the Task Manager we can find the tab that's stuck, where we have our infinite loop, that's the Tab: Plunker, right here, and we can End Process on that tab. So that completely shut down the Chrome browser. You can see the slide I had up earlier, and we still have our Task Manager, but let's create a new window for Plunker. Now when I'm back in Plunker, unfortunately it wiped out our program. So that's the importance of always being careful with your loops. If you get into an infinite loop situation you may lose your browser window. So if you're writing a lot of code make sure you save you work often.
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.
Summary
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.
Functions
Introduction
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.
Function Basics
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.
Function Scope
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.
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.
Objects
Introduction
Hi, my name is Mark Zamoyta and welcome to this module on Objects. An object lets us store related information in one place. Let's say we have an application about cities across the world. A city is going to have a name, it's also going to have a population, and it's also going to be associated with some country. So an object can group all that information together, the name, the population, and the country, and we'll be learning the fundamentals of objects in this module. We'll start off by creating a very simple, basic object. We'll see how we can pass that object to functions and manipulate it. It's very common to have arrays of objects. So far we've seen arrays of strings and other values, but having arrays of objects is one of the more common types of arrays you'll work with. Next we'll look at some of the JavaScript built-in objects. And we'll also see how to find out more information about these objects online, and we'll wrap things up by adding objects to our Blackjack game. So let's get started and create our first object.
Object Basics
An object lets us store related information together. Let's see how we create one. Here we're creating a variable, we use the let keyword and the variable name is person. And the curly braces here represent an object. And this is an empty object that will be assigned to person. In this object we're putting useful information together to become part of the object. Here we can see that we're assigning name value pairs to the object. These items are called properties. So here we have an object that's made up of three properties, name, age, and partTime. We specify name: and the value of that property, John. And you can see that John is in quotes, so this will be a string property. The next property is age and that will be a numeric property, 32, it's not in quotes. And partTime, that will be a Boolean property, we're setting it to false. So now we have this object that we're storing in the variable person, and let's see how we use this object. Here's our object again that we just created, but now we're going to log out person.name. So the way to access a property within an object is with this dot notation. We specify the variable name person., and the property name, in this case name. And that will result in John. Next we'll log out person.age, and that's 32. And finally, we log out person.partTime, which is false. If we were going to create an object for a deck of cards we could have the suit be one of the properties, that would be Hearts, Clubs, Spades, or Diamonds, and we could have the value, which could be 2 through 10, Jack, King, Queen, and Ace. And objects are used all the time in JavaScript, so it's good to get a lot of practice working with them. Let's go to Plunker. So let's create an object. We'll call the variable card and we'll use curly braces to create our object. And we can put a semicolon at the end of our let statement. And I'll go back up, and what we'll do now is we'll add properties to card. We can add a property called suit, let's say this suit is Hearts, and we can specify a value. let's say the value is a Queen. So now card is an object. We can log out card.suit, and we get Hearts. Likewise we can log out card.value, and now we get Hearts for the suit and Queen for the value. And keep in mind that we could have any kind of information here. We could have numbers, Boolean values, or even arrays, or other objects, but this is a good starting point for now.
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
It's very common in JavaScript to be working with arrays of objects. Let's go to Plunker and take a look at this. So here we have a card, we were working with this earlier, but now we want to have an array of cards. So let's change our variable name from card to cards, because we have multiple cards now, and to create an array we know we need these square brackets. So there's our opening bracket, and then at the bottom I'll put the closing bracket. And to make this clearer I'll indent this object. And I'll put a semicolon at the end of our let statement. So cards is now an array with one object in it, and let's see how we access this. We can log out cards and this is an array, so let's log out element 0.suit. And you can see that it logs out Hearts. So it works just like a regular array, we access cards subscript 0 to get the first item, but that's an object, we so add a .suit to get the suit property off that object. Now if we had multiple cards in this array we could separate them with commas, just like in any other array. We'll have the suit be Clubs, and we'll have the value be King. So now we can access cards 1.suit, and we get Clubs. We can access cards 1.value, and we get King. What is we access cards 2.value, let's look at that. We get a TypeError: Cannot read property value of undefined. That's because cards 2 is undefined. We only have access to cards 0 and cards 1. And if we try to access a property on undefined we get this TypeError, so that's just something to watch out for.
JavaScript Built-in Objects
We've seen how to create our own objects, but in fact JavaScript has several valuable objects built into it. This is a big topic so we're only going to touch on a few of the built-in objects, and only a few of their features, but I will show you how to get more information on the built-in objects. Here are some of the common built-in objects that we'll briefly cover now. First of all there's a Math object, and we're going to need this for our Blackjack game because this is how we get random numbers. When we shuffle a deck of cards we're going to need to randomly move the cards around, and we need the Math object for that. Another very commonly used built-in object is Date. It's extremely common to want to know what the date is, or how to manipulate dates. And we've been working with strings, but there's also a string built-in object that lets us manipulate strings in lots of different ways. Likewise there's the Number built-in object to help us work with numbers. And there are dozens of more objects, let's go to the Mozilla Developer Network online. I'm here at developer.mozilla.org, and I've searched for a standard built-in objects. And I'll bump up the font of it here. If we scroll down on the left side we can see some of the built-in objects here. We'll be looking at Date, and here's Math, and Number, and if we go down more we should be able to find String as well, right here. So we're just going to touch on these objects in this video, but for more information you can come here to look things over. Again, it's developer.mozilla.org, and just search for standard built-in objects. So let's start off by looking at the Math object. I'll create a variable, and I'll just name it result, and I'll specify Math, for the Math object, .random, and that's the function, so I'll add the opening and closing parentheses. And at the bottom here, I'll log out result. I'll move the Console to the bottom so we can get a better look, but we can see our large, random number here. Random returns a value between 0 and 1, so if we wanted to get a random number between 0 and say a number like 52, for 52 cards in a deck, we would just multiply this by 52. And the problem is that the number will mostly likely have decimal values that we can truncate. We can also truncate that with math. So on the next line I'll say result = Math.trunc, T-R-U-N-C, that's stands for truncate, and I'll pass it result. And now we get the random number 19, they truncated everything after the decimal point. So we took result, a random number, and passed it back into this Math.trunc function, and we assign that back to result. So we'll actually be using this later in the course when we start to shuffle a deck of cards. Another built-in object we're going to look at is Date. So let's create a Date object. We can specify new, and new is a keyword that lets us create a new object, such as Date. So now result is being set to a new Date object, and you can see the resulting string here. It's Mon Dec 18 2017, and here's the time and the time zone I'm in. Another thing we could specify is a function off of Date. We'll specify .toDateString. And that gives us a more simple form of the date, Mon Dec 18 2017, without the time. And there are dozens of functions that we can use on dates, so please see the Mozilla Developer Network to find out more about it. And as far as strings and numbers go, let's say we set result to a string, Hello World!. Because strings are objects we can write result., and any of the methods or properties that are on the string object. One useful one is toUpperCase. And we have to assign this back to result. So we'll say result = result.toUpperCase. And now we get HELLO WORLD! all in uppercase. Likewise there's a toLowerCase, and now it's all in lowercase. And again, check out the Mozilla Developer Network because there are dozens of functions that might be of use to you on strings. And let's look at numbers as well. Let's set result to 0 / 0. And earlier in the course we could see that that resulted in Not a Number, as we see right here. Now instead of logging out result, there's a very useful function we can look at. And it's on Number. We'll type Number, to access the Number object, .isNaN, and we'll pass it result. So isNaN is a function on the number object, and it results in true. If we made this a value such as 2 / 2, you can see that we get false. IsNaN of 1 is false. So number.isNaN is a very useful function if you need to test your variables to see whether they're valid or not. And we could go on looking at these objects for a very long time, but that's all we're going to cover for now. So please take a look at other Pluralsight courses and the Mozilla Developer Network to find out a lot more about built-in 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.
Summary
We started off this module by looking at the basics of working with objects. We saw how an object is a name value set of properties. Each property can be any datatype. Next we looked at passing objects to functions. And we saw that when we pass an object to a function any changes we make persist, even after that function terminates, any changes we made to the object will remain. Next we looked at working with arrays of objects. This is a very common thing when we program in JavaScript. And we looked at JavaScript's built-in objects; specifically we worked with Math, Date, String, and Number objects. And we also saw that we could go to the Mozilla Developer Network to get more information on these objects. Finally, we added objects to Blackjack. Instead of a card being as string, the cards in our deck are now objects, and that way we can easily access the suit or the value of each card. So we're getting really close to being able to finish our Blackjack application, there's just one more big piece to the puzzle. We've been working with console.log statements all over the place, and that's great for testing and development, but we need to start working with web pages, that way we could get input from the user and give output back to the user. So in the next module we'll stop using the Console and we'll start using web pages for input and output.
Programming for Web Pages
Introduction
This module is titled Programming for Web Pages. My name is Mark Zamoyta. Every application is going to need to gather input from a user, and the most common way to do that in JavaScript is through a web page. Also we would want to display output to a user through a web page. So far we've only been working with the Console, which is built into the browser, but now we can start working with HTML5 tags. We'll start this module by setting up a web page. We'll add a few basic elements and we'll see what we need to do to access these elements in JavaScript. Next we'll go to JavaScript and we'll see how to change some text on the web page. Next we'll have some buttons on our web page, but we want to know when those buttons get clicked. We'll see how to handle a button click using what's called an event handler. Next we'll see how to remove and add elements to a web page, and we'll wrap up the module by adding a user interface to our Blackjack game. So let's get started and look at a web page in Plunker and set it up to be used by JavaScript.
Setting up a Web Page
Let's set up a web page so that we can work with it in JavaScript. But before we do that there's a certain term that we need to know. The term is DOM. DOM stands for Document Object Model, and it defines how the data of a web page is organized and manipulated. So looking at this acronym word by word, document just refers to a web page, an HTML file. And model refers to the data that we use in any program. And of course we store our data most of the time in an object, so that's the object model. So you'll hear this term, DOM, often. Sometimes it's referred to as the DOM, as in we use JavaScript to program the DOM. A JavaScript developer would most likely use the term DOM, or the DOM, rather than the word web page, because as a JavaScript developer we're mostly interested in working with objects. Let's go to Plunker and see what I mean by objects within an HTML file. I hit the New button and created a new Plunk. And the first thing we're looking at is the index.html page. If we look at the output of this HTML page we see Hello Plunker!, which comes from this h1 tag right here. And this tag is also referred to as an element, and we can get access to this element in JavaScript by using the DOM. Now let's just add a few more elements, just so that we have something to work with in this course module. So after the header we can add a paragraph, and that won't have anything important in there for now, and let's also add a button. The button says Click Me!, so now we have three elements that we want to be able to access in JavaScript. And there are a few different ways to access these in JavaScript, but one of the more common ways is to give each element an ID. So for our h1 tag, I'll enter an attribute called id, and the id will be title. And our paragraph, the id will be paragraph. And for the button, let's just call this the ok-button, and we'll change Click Me! to Ok!. Now there's one other very important thing we need to do with this HTML file. Our script tag is placed on top by Plunker, but we actually need this right before the body closes, so I'll delete it out of here and I'll add it before the body closes. So when we work with JavaScript in script.js we want to make sure that all our IDs are set up. So by placing this script tag underneath all the other elements that we need access to we can be sure that JavaScript know about them. And this is really important, because if we don't do this JavaScript won't know what IDs we're talking about. So it's very important to remove the script rom the head section and place it right before the closing body tag. So that's what we need to do to set up our HTML page. In the next video we'll start working with JavaScript and access some of these elements.
Changing Text
One element that we added to our web page was a paragraph tag, a p tag. So let's see how we would go about accessing that in JavaScript and changing its text. In our HTML file we had something like this, a p tag for paragraph, and we set an id. Here the id is set to text-area, and we have it its closing tag. So to access this in JavaScript let's create a variable called paragraph and we use a special object called document, which refers to the DOM, the web page. And on that object we have a function called getElementById, and we pass it one argument, the name of the id we're interested in retrieving. So after this line executes, our variable paragraph will refer to this HTML tag, and once it's set we can access a property called innerText, and we simply assign any string to that innerText to get it to show. Let's go to Plunker and see this in action. So here's our HTML file and let's just change the paragraph id to text-area. And we want to access this now in JavaScript. So I'll go to script.js, and I'll delete the comment here, and let's create a variable to look at that text-area. We'll say let textArea = and I'll type our document object. This is built into JavaScript, and I'll call a function on it called getElementById. And I'll pass it the string text-area. So now our variable textArea holds that element, and we could say textArea.innerText = Hello World. And now we can see that our output gets updated to Hello World. So just to be clear about what we did, let's look at the HTML again, this paragraph has an id of text-area, and in JavaScript we called document.getElementById passing it that id, text-area, and we stored it in the variable textArea. And with this JavaScript variable we access the innerText property, and we can assign that whatever we would like. Another thing we could do is find out when this button gets clicked, and we'll do that in the next video.
Handling a Button Click
When the user clicks a button it fires off what's called an event in JavaScript. And we want to be able to handle that event, we want to be able to handle a button click. The first thing we need to do is to access that button, and this is similar to the way we access the paragraph. We'll create a variable called okButton and we'll use the document object, so I'll say document.getElementById, passing it the id of the button, which his ok-button. And once we have this variable set up, we can write okButton. and call this function, addEventListener. The first argument to add event listener is the event we want to listen for. And the event name is click, and we put that in quotes. The second argument is actually a function, and we haven't seen that in this course yet, but it is possible to take a function and pass it as an argument. And the way this works is, whenever the button gets clicked this function will get executed, we just need to add our code right here, in the function body. Another interesting thing is that this function does not need a name. We can declare it with the word function in parentheses. Let's set this up in Plunker. So here's our HTML file, and looking at the button tag we do have the id set to ok-button, that's what we want. We'll go to JavaScript, and let's declare our variables on top of this file, we'll let okButton equal document.getElementById, ok-button. And I'll just wipe this out for now, but we want to handle the click event on this okButton. So I'll type okButton.addEventListener. The first argument is the event we want to listen for, which is click. And the second argument is a function, which we don't need to give a name, we can just specify function with the opening and closing parentheses, and then the function body. So whatever code we enter right here will execute whenever the button gets clicked. So when we click the button let's update our paragraph. We'll say textArea.innerText = Button clicked! So looking at our web page here, the paragraph says this is some text, and let's click the Ok! button. The text gets updated to Button clicked! So this is how we set up what's called an event listener, we're looking for the click event, and this is the function that gets executed by JavaScript when that event occurs. Another thing that might be useful to us when programming the DOM is to remove or add elements to the web page, and we'll see that in the next video.
Removing and Adding Elements
Let's look at how we can remove and add elements to the DOM. Here we have an example. We set up our paragraph like we've seen earlier, we get the element by id text area and assign it to that paragraph variable. Now once we have that element stored in the variable we can access the style property, paragraph.style, and that gives us access to the CSS styling properties. We can specify style.display and set that to the string none in order to remove the element. If we wanted to add that element back into the page we can say paragraph.style.display and set that to the string block. We'll be able to see it again. So let's go to Plunker and try this out. When we click the Ok! button let's have this paragraph disappear. Again the paragraph has an id of text-area. In our JavaScript we're setting up our variables already, textArea and okButton and we have a handler set up for the click event. So when the user clicks the button we want to look at textArea.style to get access to the CSS styling, .display. And we'll set that to the string none. I'll click on the OK button, and our paragraph disappeared. And we can work with any CSS property this way in JavaScript. Let's actually take this line of code and copy it, we'll hide it to start out with, and then when the button gets clicked we'll set the display to block. So our paragraph is hidden, when I click Ok! the paragraph shows up, and that's how we toggle back and forth between hiding something by setting its display to none and showing it again by setting the display to block or if it were an inline element you could specify inline. And if you're not familiar with HTML5 and CSS definitely check out the Pluralsight courses on these technologies. The main focus here is on JavaScript. So now we know enough about DOM programming to start using this in our Blackjack game, and we'll do that in the next video.
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.
Summary
In this module we set up a web page so that we could use it when working with JavaScript. An important thing was to remember to move the script tag to the bottom of the file, it should be right before the body closes, that way JavaScript will have access to all the IDs and elements in the DOM. We saw how we could change the text on a paragraph tag, or any other element that had innerText, we specify the element name .innerText and set it to any string. We saw how to handle a button click, we get access to the button and call the function addEventListener, we passed it the name of the event we wanted, which was a click event, and we also passed in a function, which gets executed whenever the event fires. We saw how to remove and add elements to the DOM. We can take our element and access its style property to access CSS properties. So we specify element.style.display. And we can set that to none to remove it from the DOM, or we can set it to block, or some other display property such as inline or inline block in order to add it back to the display. Finally, we added a user interface to Blackjack. We set up a text area and three buttons that we can use to play the game. So now you have everything you need to know to wrap up the Blackjack game, we'll be doing that in the next course module.
Finishing Our Application
Introduction
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.
Shuffling Cards
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
There's only one more function we need to code to wrap up our game, let's take a look at it. Here's the function checkForEndOfGame, and let's see what it does. The first thing we do is we call updateScores, we saw that earlier, we just want to make sure the scores are current. Next we check if the game is over, and if the game is over we want to give the dealer the option to take cards. So while the dealerScore is less than the playerScore, which means the dealer is losing, and the playerScore is less than or equal to 21, and the dealerScore is less than or equal to 21, we want to give the dealer a new card, and we want to update the scores as well. So this loop will continue as long as there's no clear winner and as long as no one has gone over 21 and lost the game. Next, if playerScore is greater than 21 then the player lost, so playerWon is false, and the gameOver is set to true. Else, if the dealer score is greater than 21 then the player won, playerWon is set to true and gameOver is set to true. Else, if the game is over, we want to determine who won. If the playerScore is greater than dealerScore then playerWon is true, else playerWon is false. And you'll notice here that there is no condition where the playerScore is equal to the dealerScore. So in case the scores are the same the dealer wins. And this something that you could fix on your own if you'd like. And next we want to update our buttons, but I remember I actually added that logic down here in showStatus. So we don't really need to do that here in this function, so I'll take these out. Now our game should be complete, I'll hit the Save button, and let's play Blackjack. We'll start a new game, the dealer has 13 and we have 16 so let's stay. The dealer got dealt a Seven of Hearts and won, so let's play again. The dealer has 14 and we have 7, so we'll take a card, Hit!, we get the Ace of Spades, so our score is either 18 or it could be 8, but the logic to have an Ace be 1 point or 10 points is something you can add on your own for practice. Right here we're taking the score as 18, and let's Stay. And the dealer is dealt a Six of Clubs and wins the game. So we have to win a game here, let's hit New Game! So here we're dealt a Jack of Diamonds and a Jack of Hearts for 20 points. So it's looking good, let's Stay and see if we win. No, amazingly the dealer is dealt an Ace, Four, and a Three. And here's something else you might want to fix. In Blackjack if a dealer gets five cards they win, so that's more logic that you can add to this game on your own. Also in the case of a tie you might want to print out a tie message rather than just letting the dealer win. Let's play again and try to win again. So we got dealt 21 points, we got our Blackjack and we win, but we don't see a win message, we have to hit Stay, and that gives us the YOU WIN! message. So we won a game, but that's another fix you might want to make to this game. If you're dealt Blackjack, which is 21, you should immediately get a YOU WIN! message. So our game works, and it's not perfect, but you do know how to make the changes and fixes now. You have all the fundamentals of JavaScript under your belt to make it a better game. So let's wrap this up with a summary.
Summary
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.
Course Summary
So that brings this course to a close, now you know the fundamentals of JavaScript. You can work with variables, and arrays, and different datatypes that you can store in objects. You've seen how to control the flow of a JavaScript program using for loops, while loops, if statements, switch statements, and you learned about functions, and work with the DOM. We completed a beginner-level Blackjack game, and you have the skill to go into the code and alter it however you'd like. When learning to program or just learning a new programming language, it's very important to get lots and lots of practice. So go into Plunker or use whatever other JavaScript development tools you have to make lots of examples and try out all these new concepts that we've covered. Good luck creating your future applications in JavaScript.
Course author
Mark Zamoyta
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...
Course info
LevelBeginner
Rating
(281)
My rating
Duration2h 46m
Released19 Jan 2018
Share course