Learning To Program - Part 1: Getting Started

  1. JavaScript When two human beings need to communicate, we generally pick a language that both parties will understand; otherwise, it's difficult to have a conversation. Programming a computer is similar. A program is a set of instructions for the computer to carry out, instructions like add these two numbers or show this picture in the middle of the screen. These instructions have to be written in a language that the computer understands. We call these languages programming languages. Just like in the real world, there are hundreds of languages to choose from when you want to program a computer. In this course, we're going to use a JavaScript programming language. Perhaps you've already heard of JavaScript because it is a language that is popular in the World Wide Web. Almost every website you visit will have some JavaScript running as a program. I'll often talk about programs running, and I don't mean the programs are trying to get away. When a computer is carrying out your instructions in a program, we say that the program is running. Sometimes the running program is a game. Sometimes the running program is a spreadsheet. Sometimes the program is just a simple special effect when you click something on a web page. JavaScript is easy to learn and work with, and because it has become so popular on the web, JavaScript programs can run anywhere now. When you visit a web page, JavaScript runs inside your web browser, but JavaScript can also run outside of a web browser in just about anywhere. We're going to start out learning to program by writing programs in the JavaScript language and then running those programs inside of another program called Node.js. The js stands for JavaScript. What we are doing is quite common in computer programming. We'll be writing a program that runs inside of another program that runs on the computer. We'll also be using all sorts of tools, which are also programs that other people have written, so we're using programs to write our program and then run our program. The nice thing about the Node.js program, or Node as it's commonly referred to, is that Node is easy to install, and it can run on Windows, on the Mac, and on Linux, so you should be able to follow along with this course on any type of computer and operating system. The first thing you'll have to do is install Node, so I'll show you how to do that next.

  2. Installing NodeJS (Windows) Installing Node is very simple on both Windows and the Mac. The experience is very similar. Right now I'm on a Windows machine, but I'll show you how to install this on a Mac also. On both operating systems you need to launch a web browser, any web browser, and go to nodejs.org. They might redesign this home screen at some point, but there should be an INSTALL button somewhere on the home screen. Just click that. Node will start downloading. In this case, since we're on Windows, it's going to download an msi file. But as soon as that is finished, I can click it, and it will launch the installer. We're just going to take the default the whole way through. I do need to accept the license agreement. I should read through the license agreement, but I've done that before, and just click Next to take, again, all of the defaults. And eventually we'll click Install. We need to allow Node to make changes to our computer. But once it's finished copying all the new files, Node should be installed. Now we've reached the end of the installation process, so I'll just click Finish, and I should now be able to go to my Start menu, and this is Windows 8, but in Windows 8 and previous versions I can search in the Start menu. I will be able to find Node. What I want to select is the Node.js command prompt. That will open a command prompt window. If you haven't used a command prompt before, this is where you can interact with the computer by typing. I'm going to tell the computer to run Node just by typing node, and this is Node running. I can test it out by entering a simple expression, in this case just doing some math. What's 2 + 2? Node can tell me that is 4. Now I know Node is successfully installed on Windows.

  3. Installing NodeJS (Mac) To install Node on a Mac, you'll want to go to nodejs.org. On that web page you'll find an INSTALL button. Click that, and it will download a .pkg file. That might take just a little bit of time, but eventually you want to open that file, and you can do this from any web browser. Open that file, and that will launch the installation program. I want to take all the defaults by pressing the Continue button every time it appears. However, there are some steps where I have to go up and, for instance, agree with the license agreement. I might want to read that first. There's also a point just before it makes changes to the computer where I have to enter my password and allow it to make those changes. But once it begins installation, it should just take a second to write everything onto the hard drive. Then I can close the installation program and run it. I want to search for terminal. Node runs from the terminal window. That's a window where you can interact with the Mac by typing commands. I'm going to type node, that runs the program, so node and the Return key, and then just a simple expression, 2 + 2 and Return. I can see the result is 4. I know Node is installed and working properly.

  4. The REPL After you've installed Node and you've opened up the Node command prompt or on Mac the terminal window and you've typed node as a command to the operating system, Node will be up and running what we call a REPL, R-E-P-L. It stands for Read, Evaluate, Print, and Loop. That describes what Node will do by default unless we tell it to do something else. Node is reading what I type, and when I press the Enter key it evaluates what I've typed, tries to understand what I am saying, and then it computes a result. Once the result is computed, Node prints the result, and then it loops back to the beginning so I can type more commands. It'll do that infinitely until I tell it to quit. This is just like having an interactive conversation in real life almost. You say something to the person beside you in a language they understand, and they can respond to you. Then it's your turn to say something again. In this case, the language is JavaScript. It's the only language the Node program understands. Two plus two is a legal JavaScript expression that Node can evaluate to produce a result. It turns out that JavaScript has a number of mathematical operations that you can do. There is addition, so 2+3 is 5; there's division, so 2/3 is 0.66 repeating. Of course you can do subtraction, 2-3 is -1; and you can do multiplication, which is 2 asterisk 3, sometimes we call that asterisk star, so 2*3 is 6. I can also have JavaScript compare numbers. So I can ask is 3 greater than 5, and the answer is false. Three is not greater than five. So I can ask if 3 is less than 5, and the result is true. And then I can ask also if 3 is equal to 5. Notice I'm using two equal signs here, not just a single one, and that's important. Is 3 equal to 5? The result, of course, is false. We'll be talking about what a single equals sign means later, but these values of true and false they're something of immense importance in computer programming because we use them all the time to make a program behave differently under different circumstances. For instance, in a game you'll want to know if it is true that the user has any health points left. Are health points greater than 0? If so, we can keep playing. In a business application you might want to know if it's true or false. Is the user a preferred customer because you'll show them different options depending on their status. True and false are so important. We'll return to talk about them many times in these videos. Of course you can't type just anything in the node REPL and expect it to respond with an answer. You have to use symbols and characters that Node understands. For instance, I can type the word lunch, and Node will respond with an error message that is in essence saying I don't know what you're talking about. Sometimes you might type something, and Node goes into this mode where it shows period, period, period or dot, dot, dot we call it. It shows that instead of a result. This usually happens because you've typed something that is not legal in the JavaScript language or something that Node thinks you need to type more JavaScript into the window to make this something that it can evaluate. And sometimes this scenario is frustrating because it feels like suddenly you can't escape from this no matter what you type. And sometimes it can produce an error. And if you ever get into this situation, you can type .break, which essentially tells Node to give up what you're trying, and let's just reset and go back to the Read step. You can also hit Ctrl+C to do the same thing as .break, that is hold down the Ctrl key and press the letter C. You can also at any time type .help, and Node will show you a list of commands that it understands. These are not JavaScript commands, so .break is not anything to do with JavaScript. These are commands that are special to Node and cause it to do something typically more dramatic than just evaluate your expression. You can save a file, you can load a file, you can exit the REPL and return to the command line. We'll see some of these file operations in a later video, but for now if you want to get out of Node of course you can always just close the window, but you can also type .exit.

  5. The Lunch Variable Let's go back to the Node REPL. Earlier I typed the word lunch, and I saw an error message. Computers are pretty simple this way. If I say the word lunch to you, you might infer that I'm hungry and I'm ready to go somewhere to eat. But the critical idea to remember about programming is that you have to be explicit about everything you tell a computer. If you want a computer to know what lunch is, you have to declare a variable and make an assignment. So I'm going to say lunch, one equal sign, 'pizza' and hit Enter. So there are a number of things to talk about in this one line of code. First, lunch is now a variable. A variable in a computer program is something that we can use to store things in, something we want the computer to remember. The computer will keep track of what we store in a variable. So you can think of a variable as a named storage location. It's like having a storage locker identified by a word. And in this case I can now type lunch again, and instead of getting an error, Node and JavaScript they remember the value pizza. I don't get an error. Secondly, what I've made is known as an assignment. I've assigned the value pizza to the variable lunch. I've done this using a single equal sign. It's like putting away pizza into the storage locker. I can reassign the variable to a new value too. That's what makes a variable variable. It can store varying different things, so let me assign the value fish and chips into the lunch variable. So we have a variable, we have an assignment, and the values pizza and fish and chips they're what we call strings. Strings are a sequence of characters. So A, B, and C, those are all characters, and I put them together inside of single quotes like this, and it's a string, abc. In JavaScript you can use single quotes. You can also use double quotes. Both of those will produce and build a string. Just put any characters you want inside. Most of the keys on your keyboard will produce a character, even the number keys. So I can also put numbers into a string because numbers can be treated as characters by most programming languages. So saying that lunch is a 12 inch pizza, 12 inch pizza is just a string of characters, and that's what is now stored in lunch. Strings are popular in all types of programs and software languages because we can use strings to do things like display text to a user and give them information. But strings aren't the only types of things that we can store in a variable. We can also store numbers. And that's quite useful because we saw earlier Node can tell us what three times four is, I demonstrated that, but we rarely write a program where we will multiply two known numbers together. Typically what we have to do in a program is to take some data, get some input from a user or from a database, and we store that input into variables, and then we perform some sort of calculation. The data and the variables, they'll hold different values. Sometimes it's a 3, sometimes it's a 4, sometimes it's a 144. We store that in a variable. So, for example, sizeOfParty = 4. This would be a way to store the number 4 into a variable named sizeOfParty. We will use sizeOfParty to hold the number of people at the lunch. It could be a five; it could be a one. We'd have to get some human input to know for sure, but for now I'll just put in it the value 4, and this is a number, not a string, a number that we can do math with. We'll talk about input in a future clip. For now I just want to demonstrate that I can store a number in a variable. Numbers or strings, either one will work. Let me create another variable. This one will be totalCost, and I'll put the value 14.99 inside. This represents the price of a 12 inch pizza. And now I have two variables with numbers inside, and I can do some math again. Let's do totalCost / sizeOfParty, and Node has just computed the average cost per person at the lunch. Let me actually save that value into a variable. So I can say that averageCost = totalCost / sizeOfParty. And now I can reference averageCost from anywhere just by using that variable averageCost. And by the way, if you hit the Tab key while you're typing in Node, it can help you automatically complete variable names that it knows about. So if I type tot and hit the Tab key, the Node REPL will expand that out to totalCost because that's the only variable I have with a name that starts with tot, so Node just fills in the rest of the word for me. Now let me put something together that will display a message to the user. We'll store something in a variable called message, and I'll say 'Your lunch ' of + lunch + in a string ' for ' + sizeOfParty + ' people will cost you ' + averageCost. And now I have a variable message that holds a string, something that we can display to a user to tell them how much their lunch is going to cost. And here you see something new again, the ability to add strings together to create bigger strings. Again, a technique you'll certainly run into when programming, a technique you sometimes use to build output or something to show to a user, something that would display in a window or a message box. When JavaScript adds strings together like your lunch of + lunch, what it does is concatenate those, put those together, and give you back the bigger string as a result. And when I have a number like averageCost, you'll remember we put a number into there, a calculated number, when I concatenate that into a string, it takes that number and starts treating that number as a string, so it's just adding into the string. And that produces the output you're lunch of 12 inch pizza for 4 people will cost you roughly 3.75. And that's stored inside of message, and generally you can have as many variables as you need to store values for your program. You're typically only limited by the amount of memory on the computer, which these days even for small devices like a phone, it's rather enormous. One thing you'll notice about these variables is how they are one-word names. This is true in most computer languages. I cannot have a variable named average, space, cost. It's just averageCost, all one word, no space between the words. JavaScript programmers generally use a lowercase letter for the first letter of a variable and uppercase letters if there's another word that starts inside the variable name. It's a naming convention that we follow. Conventions are extremely useful in programming languages because it means we all write code in a similar fashion, and that makes it easier to read each other's code. Whenever you learn a new programming language, whether it's JavaScript or C++ or Java or Ruby or Python, you should try to discover the conventions that most programmers follow for that particular language, how they name things, how they space things, and follow those conventions. We'll talk about JavaScript conventions throughout this course.

  6. Getting The Most I have three pieces of advice for you to get the most from this course. First, follow along with everything I type. Programming has to be learned from experience. It's impossible to learn otherwise. Type along with me, and make sure you see the same results. Pause the video if it's going too fast. Go back and restart this video if you haven't typed anything as yet. The second part of my advice is to be precise. Double check every character you've typed if you're not getting the same result as me in the video. JavaScript is very particular about the characters that you type. The single quotes have to be in the right place. The plus sign has to be in the right place. For the most part, spaces are a bit fluid. You can have one space between a variable and a plus sign or two spaces or no spaces. And the only place where spaces are really significant is inside a string because sometimes we need spaces to break up words and display the correct output, but the rest of these characters and the variable names and the mathematical operators you have to be very precise about those. Finally, feel free to experiment. I'll say it once again. Experience is what makes you a better programmer, and having some curiosity will help too. Try things with different numbers, different operators, poke around and find new error messages. It's okay. Every time you get a new result, you've learned something new, and learning builds your experience, which is I've already said twice, that's what makes you a better programmer.

  7. A Summary We are now at the end of the first module in this course. We've installed Node, and we've used the REPL to run some simple JavaScript code and compute the average cost per person for a lunch bill. We're going to build on what we've learned through the rest of this course and write more complex JavaScript programs as we move forward. We'll be talking more about strings and numbers and variables and how to use true and false, and we'll have a lot of fun through the rest of this course. I'm very happy you've stuck around so far, and I think you will find the craft of computer programming to be very rewarding.

  8. Learning To Program - Editors and Code Files Introduction Hi. This is Scott Allen, and in this module we're going to learn a little more about using source code editors and other tools to write some JavaScript programs. If you followed along in the introduction, we spent a lot of time in the Node REPL. That's a great way to experiment with JavaScript and get started, but to really write a program we're going to need an editor. An editor helps us write JavaScript code, and we need to create JavaScript source code files and save those files on our computers. That way the program stays around, and we can run it tomorrow or next week or next year. This module is going to show you some of the basics of working with a source code editor, managing JavaScript files, and using Node to execute the JavaScript for a program in a saved file.

  9. Text Editors When you write JavaScript code for a program, you typically write more than just a few lines of code, so it's useful to have a good text editor for your JavaScript source code. A text editor is a program that lets you write as many lines of code as you need and then save the code into a file for later use. Then some time in the future you can open up the file and make some changes. An editor can be very simple. It just has to be able to save text files, and nearly every operating system comes with a basic free text editor. In Windows there is Notepad; on the Mac there is TextEdit. The more you program, the more you'll probably want to use a more advanced editor because advanced editors can actually understand JavaScript code as you type and help you program. Just like a real life editor can review pros and help a book author, a JavaScript editor can help you catch common errors and make suggestions. But before we go to a slightly fancier editor, let me show you what editing JavaScript in Notepad looks like because you can use simple editors like Notepad and TextEdit if you want. This will also give us a good understanding of saving files and then being able to run them in Node. Alright, let's go into Windows and open up our Node.js command prompt. From here what I can do is now I'm going to launch Notepad. I can do that from the command prompt just by typing notepad. I could've also have done that from the start menu by searching for Notepad and clicking on it. But I already have an instance up, and I'm going to type some code that looks pretty much like what we had in the REPL the other day, but with a few differences. I'll explain what those are after we figure out how we're going to save this and run this in Node. And now I want to save this file. And by default it wants to save in my Documents folder, which is okay, but sometimes you want a little more structure in the file system. You want a specific place where you can save your source code. So let me go into the area here and either right-click and say New Folder and add a new folder here for my project, or I can also do this from the command line. So if I go into my Documents folder, I'm going to mkdir or make a directory called GettingStarted, and then I can cd or change directory into GettingStarted. And the tab auto-complete also works here on the command line, and it's inside of here where I really want to save the file. So let me go back into Notepad, and I can see it has refreshed. It now has my GettingStarted folder, and down here I'm going to say I want to save this as program.js. And one little thing you want to do in Notepad is to make sure that you select all files here; otherwise, it tries to save it as program.js.txt with a txt extension, but I want this just to be program.js. JavaScript source code files always end with a .js extension. That way you can easily identify them on disk and know it's a JavaScript program inside. So I click Save, and now I have a program saved that I can run from Node. I can just type node program.js, hit Enter, and it displays pizza. Perfect! What's nice about having my program in a file, of course, is that I can close Notepad, I can shut down the computer, I can open it up a week later, and I can come back into this command prompt and I could say dear notepad I want to open program.js, and now I can make changes. So instead of pizza for lunch we'll have fish and chips. I'm going to save that. Let's run it in Node again. Now we have a different answer. If you're doing this on a Mac, you go through basically the same steps in the terminal window and using text writer, but just make sure when you save the file in text writer do not save the file in the Rich Text Format. Save it as Plain Text. Node will not understand JavaScript saved in the Rich Text Format.

  10. Smart Editors There are hundreds if not thousands of different text editors that you can choose from on Windows and on the Mac. Some are free, some will ask you for donations, some will require a paid license in order to use. I don't want to give you specific recommendations, but I am going to use a different text editor than Notepad here on Windows. I would encourage you to go out to a search engine and search for JavaScript editor or text editor, look at the reviews, download a few, try them out. Pick the one that makes sense to you. Pick the one that works the way you would expect it to work, and it looks good, and you are happy with its appearance. The program I'm going to use is Notepad++. And again, you don't have to use this. It's just the one that I picked. It's a free, completely free, open source text editor. It's available for download on Windows only, but it will give you an idea of what a good text editor can do, a good text editor that knows a little bit about JavaScript. I've already been to the Notepad++ website. I've clicked on the download link. I've run the installation program. It's a very easy setup. And now what I can do is go into Windows and search for Notepad++ and open that up. And now I can go to the file menu. Let's open up in the Documents GettingStarted folder that we just created our program. There it is, program.js. Then I can load it up in Notepad++. It's the same program we've been working with. Now one of the first things I usually do with a text editor that has an all white background is I change that color because programming for long periods of time against a white background, it just doesn't work for me personally. You might like it, but it's not for me. Fortunately, Notepad++, if you go into the Settings menu, there's a Style Configurator, and there are a number of different themes, all sorts of different color schemes that you can try out. I'm going to pick one called Vibrant Ink. And again, this doesn't matter to our JavaScript program at all. This is just about the interaction between me and the text editor and what colors I like. I'm going to pick Vibrant Ink. I'm also going to bump up the font size a little bit so that it's easier to see the code. And there's the same program that we've been working with. I can now make changes in here, type in things like pizza, go and save the file or just hit Ctrl+S as a shortcut key to do this, and this should still run in Node just fine. And you might've noticed one of the benefits of using a text editor that actually understands JavaScript a little bit is that it knows what a string is in JavaScript. It's something between double or single quotes, and it will color it differently. It understands that equals is an operator, an assignment operator. That's colored differently than the variable name and some of the other pieces of the application that we're using. It might seem silly, but these color schemes actually work really well because they make the code a little more readable. As we add more and more code, it's going to be easier to pick out variable names and strings that we need to change. It's nice to have this feature. It's called syntax highlighting. And now, speaking of syntax, you might remember in the REPL what we did in our program was we just typed in lunch after we had made an assignment to lunch. And let me save this file and run it. And when we did that in the REPL we would still be able to say pizza as the output. But that's what the REPL does. If you type in just a variable name and give it just that variable name, it's going to dump that variable name out on the screen so that you can see what is in the variable. But once you actually start using an actual js file, just having that variable name on a line doesn't produce any output. You have to be very explicit about when you want to write something to the screen. In application development, a screen like this is commonly called the console. And so what I want to do is write the value of that variable into the console. That's what this line of JavaScript does. I'm saying dear console, please log the following variable, that is output it, put something on the screen, console.log(lunch). And I could console.log(lunch) multiple times if I wanted to and save that and run the program again, and I get pizza three times. Now we'll come back and talk about this in more detail in later videos, but for now let's just review the program that we have so far. We have a variable called lunch. We've assigned to it the string value pizza. We have this thing in JavaScript Node called a console. When I want to interact with the console, I can say console., and then you can think of this as giving the console some sort of command, dear console I want you to log something. And then I'm passing in parameters as to what log should do, what variable should it use. I can pass in lunch. I could pass in the value 4. And if I pass in the value 4, now what we'll get is pizza pizza 4. And I can pass all sorts of different things in the console.log. It all depends on what I want to show to the user. But for now just know there's a console, I can give the console a command like log, and I can tell log exactly what I want to display. There are other things or objects inside of JavaScript that we can interact with to do input and output on the file or get input from the user on the keyboard when we type in. We'll look at all that. But before we do that, let's talk a little more about JavaScript syntax.

  11. Syntax Rules When we talk about the syntax of a human language, we're typically talking about how to construct a sentence that is valid for that particular language. And when we talk about syntax for a programming language, we're talking about something conceptually similar. Every programming language has a specific syntax, and the different languages their syntax can be quite varied. But the syntax is how you arrange the code for the language to understand it. JavaScript has a particular syntax. It says when you want to assign a variable you put the variable on the left hand side of an equals sign and the value to assign it on the right. JavaScript will know what to do from there. I'm going to add a little more syntax to our program. First I'll come into the opening line of code and add a var keyword before the variable lunch. Var is a keyword in JavaScript syntax. That means it is a word that has a special meaning, and var's special meaning is that it tells JavaScript explicitly that we want to declare a variable. In this case, the variable is named lunch. It's a good idea to always use var when you declare a new variable. It's optional to use var, you don't have to do that, we saw the program work without it, but it's what programmers call a best practice because it's best if you just use var. You can create strange bugs and errors if you do not use var. And I can use var as many different times as I want to declare as many variables as I want. So I could come here to the bottom of the program, declare another variable called Scott, and that's using the var keyword. Now if I'm only using a variable that's already been declared with var, I don't have to use var again. In other words, if I have to use name on this line of code, I don't have to use the var keyword there. I can just same name = "Allen." But the first time when I intend to create that variable, something new called name, that's where I should always, always, always use the var keyword. And now that we have something called name, I could also log, which is a way of saying write this to the console. And that works. The second thing I'm going to do is I'm going to come in and add a semicolon at the end of each line of my JavaScript. Semicolon is also optional in JavaScript, and I'd already out of habit put semicolons at the end of var name = "Scott." But semicolons are optional in JavaScript. You don't have to use them. We saw the program work without them. But most JavaScript programmers, not all of them, most JavaScript programmers will use semicolons in JavaScript whenever they can be legally be placed. The semicolon is a lot like a punctuation mark at the end of a sentence. It says this piece of the conversation is done. Now take a breath and move onto the next piece of the conversation. In other words, I'm declaring a variable to hold the value pizza, and now semicolon, stop. The next thing to do is to log to the console and then another log and then another log. It might be confusing at first to know when you should have a semicolon and when you shouldn't. They don't always appear at the end of a line. But if you stick along with this course, you'll learn when to use semicolons. I'll always use semicolons from here on out. A semicolon would be a little more obvious if I were to let's say not have console.log on a separate line. If I did this without a semicolon there, I would get a runtime error because JavaScript would get confused. It's like having one big long run-on sentence in English. Var lunch = "pizza" console.log. Hmm, what exactly was I supposed to do there? But with a semicolon there it is two different JavaScript statements, just on the same line of code, and the program should still work correctly. That being said, most programmers would not put all of this code on one line. They would put them on separate lines because they do two different things. And I even add a little bit of space here between var lunch = "pizza" and the console.log. That's not required. That's just stylistic. There's a lot of aesthetics to writing computer code. You want it to be easy to read. You want it to be easy on the eyes and appear nice. And sometimes just having a little space in the right places to break things up makes the code easier to read. But you would almost never cram together two lines of code, two separate statements on the same line. That makes it harder to read, so I'm going to leave console.log down here. And as we continue, I'll talk more about aesthetics and when to use a semicolon and when not to use a semicolon, so we'll get there with all of this.

  12. When To Panic Sooner or later you will run into an error when running your JavaScript program, and my motto is always try to get there sooner rather than later. Sounds like strange advice, but in other words play around with this JavaScript program and see what types of errors you can get because it's a lot easier to fix errors when you know exactly what you changed to produce the error. And the experience, there's that word again, the experience that you gain from diagnosing errors is invaluable because it will save you time when you have a real error and you don't immediately know where it came from. You've seen it happen before; you won't panic. That's the most important part, do not panic. Node will try to help you find the error. Let's take, for example, the scenario I was describing before where we put console.log on the same line as var lunch = "pizza." And I save the file, I try to run the program, Node will give me an error. The useful information here is that it will tell me the file name and line number. The file name is very important when we start using multiple files later. And in fact, just below that, it's actually pointing to the unexpected identifier. That's the actual error that it's giving me, SyntaxError: Unexpected identifier. It didn't expect a console. That's because we're doing this variable assignment putting pizza into lunch, but then console where did it come from? Not sure. JavaScript gets confused, throws this error, and stops executing. So that's an easy one to fix. I just need to have a semicolon there, and I'm going to keep that line of code on a different line. And now let's try something else. Let me purposefully accidentally put a space in the word log and save the file and try to run this again. What we'll see is that we again SyntaxError: Unexpected identifier this time on line 2. And again, Node will point me right to the offending G. It's not sure where this G came from. I just happen to have a space in there that shouldn't be there. Sometimes it's legal in JavaScript to put spaces in places. For instance, I could put console space dot space log. And if I save the program, that works just fine. But other places you cannot have a space. If you have an identifier like console or log, we need those to be all one word for this to work with Node. And finally, something else I've pointed out before indirectly, JavaScript is a case-sensitive language. So if I have an uppercase variable called Lunch, that is different than a lowercase variable lunch. And if I save that program and run it again, Node will actually come and tell me lunch is not defined. You're using a variable that you haven't told me about. That's a ReferenceError. I would have to go through and put uppercase for all the other lunches in all the console.log statements. But instead of doing that, instead of using an uppercase, I will start this with a lowercase L because that's the convention in JavaScript. That's what most JavaScript programmers do, lowercase L. So try a few other things. You might be surprised at what doesn't produce an error in JavaScript because it's a pretty malleable language. You can omit semicolons, you can have multiple lines of code on the same place, you can put spaces in weird places. For instance, var name = "Scott." I can put as many spaces there as I want, and the program is going to be just fine. That doesn't produce an error. But see if you can find some other situations that do create an error and get used to those error messages. These types of errors are the good errors, or at least they're the errors that are easy to diagnose because you get a line number that tells you right where the problem is. Later we'll be looking at different types of errors and bugs. Things that do incorrect computations and display the wrong values to user, those are the types of bugs that are hard to track down. Those don't stop the program like this. This is JavaScript stopping the program because something is terribly wrong and it can't move forward. Those other bugs, sometimes they're harder to catch. The program keeps running, but it's giving the wrong results. Sometimes it takes a while to even detect that there's a bug in the software, but we'll talk about those later in the course.

  13. Check Please Before we leave this module, let's do something a little more interesting. I'm going to go in and select all of the code that we've written so far and just delete it. We're going to return to a scenario that we were trying in the last module, that is computing the average cost for lunch, only I'll do it a little bit differently this time. And now we're not in the REPL. We're in a text editor. We can write a full program. So first of all I'll declare a variable totalCost and include a semicolon at the end. I'm using the var keyword. That's going to hold the total cost of the lunch. And then what I'll do different compared to the original scenario is instead of hard coding the size of the party or how many people are coming to lunch, I'm going to ask the user to tell me how many people are in the party. When I say hard coded, I mean I'm literally putting a value here like the value 4. I'm not taking user input; I'm not trying to find that data. That's what we call hard-coded into the file. So instead of hard coding it, I want to be able to get this from the user. And the question is how do I get this from the user? Well, Node makes a number of objects available about its environment. For instance, console is an object that I can interact with and do something like console.log to write out to this output window. Another object that I can interact with is the process object. Now the question is what can the process object do for me? And this is where the REPL is interesting if I start up the Node REPL because I could go into the Node documentation and see what is available for a process, but I can also go into the REPL and type process. and then hit the Tab key. Node will expand out everything that's available through the process, all of the different commands I can give it, all of the information I can get out of it. So, for instance, process.title will literally give me the title for this window. And by the way, what is a process? Well, we usually call a running instance of a program a process. I can also walk up to process and say what is the version? It's version 0.10.4. Another thing that is available on process is a property called argv. So you can see it contains the value node. And since I have this funny square brackets thing, we'll talk about that later, but argv is essentially any parameters that the user passed to this program on the command line. What do I mean by that? Well, let's exit out of the REPL for a second, and let me temporarily use the console.log to dump out progress.argv. And I'll save this file. And now I'm going to run it as node program.js, and then I'm going to pass some extra things in like pizza lettuce onion and run this program. And you can see these extra parameters that I passed on the command line, when we dump out argv they are available in here. There's pizza, there's lettuce, there's onion. There's also a node, which is the process that I'm running, and program.js, which is the JavaScript file that we loaded in here to execute. So while my program is running if I can get to argv and if I can look at these values inside of here, well the user, what I want them to be able to do is type program.js with a 4 or a 5 or a 6. Tell me how many people are in the party, and then I will grab that value and use it to compute the average cost. So the way to do this with Node is to say sizeOfParty is the name of the variable, and we will assign that process.argv sub 2, so funny square brackets. This is an array in JavaScript. An array can contain multiple items inside of it, so think of it like a variable. But it doesn't just hold one value; it can hold multiple values. And I'm asking for a very specific thing out of this array. We're going to return later and talk about arrays in more detail and about this funny syntax, but for right now just trust me it's going to pull out the value that the user types after program.js, whatever they type in there. So then I can say that the averageCost equals the totalCost divided by the sizeOfParty, and now I can write that out to the user, averageCost. Let's save the program and come back in and try it out. Program.js, three people in the party, let's run it. It looks like the average cost is just under 5. Is it five dollars, five Euros? I'm not sure. Maybe we should make that output more clear. I'll go in here and put a dollar sign + averageCost. Remember, that will do string concatenation for us, turn this number into a bunch of characters, concatenate it to the end of the dollar sign. Let's run this once again. Let's say we have a lunch with two people. That'll be almost $7.50. What about a lunch with six people? That's about $2.50. A lunch with 10 people, only one pizza though, but you only have to pay about $1.50. And so now what we have is a Node program that has some variables that hold numbers. We're taking some input from the user by looking at what they typed on the command line, doing some math, doing some calculations, and then producing some output.

  14. A Summary In this module we saw how to use a text editor to create a file with a js extension, and we wrote some JavaScript source code inside of that. We can then load that file into Node, and Node will execute the JavaScript code inside the file. We got a look at how to read command line arguments using process.argv. That's an array. We'll talk about arrays in more depth in the next module when we talk about some of the different object types in JavaScript.

  15. Learning To Program - Variables and Types Introduction Hi. This is Scott Allen, and in this module of Learning to Program we're going to talk a bit about variables and types. Nearly every computer programming language has variables of some sort because variables are incredibly useful. A variable allows us to store some data in a program and retrieve the data at some later point. You can think of variables like variables in algebra. But if you don't like math, don't worry. I won't ask you to solve any equations. I just want to show you how variables work. I also want to talk about types in JavaScript, and we'll drill into some of the funny syntax we saw for arrays in the last module. I hope, as always, that you'll follow along, pause the video if need be, and try your own experiments.

  16. I Declare Here we are in our text editor again, and I've just started a new file for JavaScript code. I called this one variables.js, but feel free to use any text editor and any file name that you like. I have one line of code in here. It says console.log, and it passes x inside of parentheses to console.log. We've seen this in previous clips. What I must be trying to do here is display the value of x in the Node command window. But let's try it. If I type node variables.js, I get an error, a runtime error x is not defined. So JavaScript is telling me yes I see that you're trying to use a variable called x here, but I don't know what x is, so I'm just going to stop and throw an error. And obviously what we've learned before, even in the first module, is that I need some sort of variable declaration, and we can do that with a var keyword. So var x, that first line of code, now creates a variable called x. That's a storage location. It's like going out and renting a storage locker. But I haven't put anything in there yet, and I just want to show you what happens if I now console.log the variable x and there's no value inside of it. What we get is undefined. So this is a slightly confusing scenario in JavaScript, but I just ran the program, and it ran successfully. It ran to completion without any errors. It output undefined, which literally means yes I see your variable x, but there's nothing there. It's like renting the storage locker, but not putting anything in it. Undefined is kind of like saying well it's empty, it hasn't been assigned to, you've put nothing in the variable. And that is different than x is not defined. So there's undefined, and then there's not defined. Not defined is an error. It brings the program to a halt. That's a program crash. It stopped. It stopped because JavaScript refused to go any further. It's basically telling us that the syntax of the program is wrong. You're trying to use something called x. I don't know what it is. I'm going to stop. At least now it knows what the variable of x is, and it can run successfully. It's just that we output something that wasn't useful. Typically what you want to do is create the variable and then do an assignment, and you can do that all on one line and say x = 3, or you can declare the variable and at some later point put some data inside of it. So I'll put the value 3 inside, save the file, obviously now we get the value 3. And this is what makes variables so great because we can declare a variable and then read some data from user input, read some data from a file, grab some data from over the network from somewhere, and we store that data in the variable. And then it's in that variable for the rest of the program. So I could go off in this program and so all sorts of other fancy algorithms, do all sorts of other work, have all sorts of other lines of code, but that value inside of x will always be there unless I change it. So think about what this program should output now. It should output 3 and a 3 and a 5. Let's just save it to make sure. And there's 3, 3, 5. And I can have as many variables as I want. So after all that work is done, maybe I need another variable called y. We'll give it the value 2, and then we'll also write it to the console just to make sure that we get 3, 3, 5, and 2, which is perfect. Now most JavaScript programmers, when they know they need a variable x and a variable y, they'll take both of those variable declarations and move them to the top so they're right at the very top. I can see that the rest of this code it has an x variable and a y variable available. And if I save this file, it should work the same as what we had before. It doesn't make a difference if I define that y at the bottom or at the top generally speaking as long as it's been defined before I do the console.log(y). And then some JavaScript developers when they need two variable like this, x and y, they'll just use one var keyword. And you can do a statement that has multiple declarations inside of it. So I can say var x and y. And, by the way, y equals 2. Again, saving this file and running it, it still works the same 3, 3, 5, 2, just a slightly different syntax that's available in JavaScript when you want to declare multiple variables. And I certainly could've started off x with an assignment here also, so start off x with a 3, y as a 2. It's still essentially the same program that we had before, just a slightly different syntax. And this is one of the things that you'll run into with programming languages. There are multiple options available to reach a certain point, to reach the goal that you want to get to and produce the right output, but quite often you have some flexibility in how you arrange the source code. And maybe you just want to arrange it so things are symmetrical and aesthetic at least to your eye. And quite often those types of changes in the program they don't affect the output at all, we still have 3, 3, 5, 2, but to some people this would be more aesthetic because x and y are on separate lines. JavaScript has a rather flexible syntax in this sense, and that can make it confusing because you're not sure if things are supposed to be on one line and where the semicolons go, but you'll figure all that out as you get more experience with JavaScript. It's a flexible language, you'll see it written with lots of different styles, but ultimately you'll have to pick the style that you like.

  17. Types The values that we assign to a variable have a type, what we call a data type. A data type is a classification for a value. For example, a value like 2, what is it? We call it a number, but what does JavaScript call it? Something like Hello inside of quotes, I called it a string in the introduction, but what does JavaScript think it is? Most programming languages recognize specific data types, some more than others, but I want to show you some of the data types that JavaScript understands and then tell you why types can be important. The easiest way to understand the type of something in JavaScript is to use an operator we call the typeof operator, literally the word typeof in front of a variable. And now I'll no longer be writing out the value to, which is what y contains, I'll be writing out the typeof y. So if I save this program and run it, we can see that y is number. And what if it's a 2.5 instead of a 2? That is still a number. JavaScript considers integers and floating point numbers, they're all just numbers. Now another way I could've written this would be to say var type = typeof y, and now I could use type inside of here. So now the variable type contains the typeof y, and the typeof y is of course a number. We already learned that. And I could've, if I wanted to, just say what is the typeof 5? What is a 5? Well, a 5 is a number too. A five is a number, what's inside of why is a number, so that's one data type that JavaScript understands, number. And now let me clean this program up a little bit, remove some of these other console logs that might be confusing. What if I have another variable called z and I put a value 3 inside of it, but it's inside of double quotes or single quotes? You can use either one that you like. I've already told you that is a string. What does JavaScript think it is even though there's a number inside? Let's do a typeof z and save and run this, and I can see that is type of string. So even though the number 3 is inside of the double quote, what JavaScript sees is a string. Because there are quotes there, that is a 3. And what if I wanted to see if x was greater than y? I want to perform that test and assign the result of that test to the variable result. So is x greater than y? First let's log the result, and then let's log the typeof result. So is x greater than y? I would expect that to be true, but the program says it is true. Three is greater than 2.5. And the typeof result is Boolean. So JavaScript understands Booleans, which are true or false values. It comes from Boolean logic. We'll be exploring that in more depth in a future module when we start talking about control flow and branching the program into different paths depending on the result of some sort of test. So there's Boolean, there are numbers, there are strings. Let's do one more interesting thing. Let me console.log the typeof console itself. So console is something that we're interacting with. We give it commands like log. What happens if we ask it for its type? Well, its type is object. There are lots of things in JavaScript that are typeof object, and we'll explore objects in more depth later on. Objects can do all sorts of interesting things. You can give them things like log that are commands that you can invoke and pass log a parameter like typeof console to tell it what it needs to log and what it needs to put on the screen. And now let me clean this up just a little bit more. What I want to output is just the typeof result, the typeof y, the typeof z, typeof console. What this will list for us now are most of the built-in types in JavaScript. There are still a few missing, but we'll talk about them later in the course. There are Booleans, there are numbers, there are strings, and then there's object. There are a whole bunch of different things that'll be of type object. And now let me tell you one more thing about JavaScript. Even though y starts off with the value 2.5 and its type is a number, I can always reassign y, and in JavaScript I can always put anything inside of y. So I could say y now equals the string Hello inside of double quotes. And let me copy this line typeof y and paste it here. What we're looking for is this value. What is it? It's of type string now. So y was a number when we output it here, but then when we set it to Hello what it contains now is a string, so we get typeof string here. And now let me tell you why all this is really important. I'm going to take out the Hello part and the typeof y so we're just back to some of the basic JavaScript types here, Boolean, number, string, and object. The reason data types are very important is because the typeof something often determines what you can do with it, so for instance, numbers. We know from earlier that it's easy to do math on numbers. So I could say what is the answer of adding x and y, and I will console.log the answer and console.log the typeof answer. Take a minute to think about what this response should be. We're looking for the first two outputs in the program, and of course the result is 5.5. That's correct. If you add 3 to 2.5, you get 5.5. And then answer, the typeof answer is number. It contains a number. But what happens if I do x + z? So this is where things get interesting. You start to do operations on two different types. X is a number, z is a string, so what do you think the value of answer will be, and what do you think the typeof answer will be? Let's save the program and find out. What we get is 33 type string. Perhaps not what you were expecting or maybe it was, but this is what can happen when you mix and match data types. You have to be very careful about data types. JavaScript tries to make things work for you, and when it sees that you're using the addition operator and something inside of here is a string, it assumes what you want to do is build a string, concatenate strings together, so it takes that value of x, that first 3, converts it to a string basically, and then concatenates the 3 with the other 3 to give us a 33. And this would happen even if we did z + x, in other words just reversed the order of those two. I still get 33 of type string. And now what would happen if I did x * y, try to get an answer for this? Well now of course we multiply 3 and 2.5, so we get the output 7.5 typeof number. That's reasonable. That's what we would expect. What happens if I multiplied z * y with z being a string value 3? In that case I get the same answer because now JavaScript looks at this scenario, and there's no built-in definition for multiplying two strings together. That just doesn't make sense. So it says you want to do multiplication. Obviously I need to convert this string into a number, so it just turns 3 into a number, and now we actually get a mathematical result instead of some sort of operation on string. Let's go back to this scenario. What if I wanted to do addition z + y, but not have string concatenation? So in this case the string concatenation z and y it was taking a 3, converting 2.5 to a string, so I get 32.5. What if I didn't want string concatenation, I wanted the answer 5.5 just like I get when I add a real number x to y? Well, in that case, I have to make sure that both of the variables here are typeof number. That way JavaScript will do real addition and not try to do string concatenation as it is doing because one of these is a string. One way to do that in JavaScript is to use something called parseInt. ParseInt is a built-in command in JavaScript. Just like console.log, the way I invoke this command is to use parentheses and pass in a value. In this case, the value is the string that I want parsed. And what JavaScript will do is go into that string, try to find a numerical value inside of there, and turn it into a number. So by having parseInt in place, when I take 3 and 2.5, I get the result I now expected perhaps, which is 5.5, and the result is a number. So there are a lot of different concepts that I've introduced you to in this clip, for instance this thing like parseInt. We'll talk about that in more detail actually just in the next clip of this module, but all I want you to think about for now is the concept of data types. Everything that I use has a data type. All these values and variables I can walk up to them with a typeof and ask for what's the typeof 2.5, what's the type of y, and that data type determines how JavaScript will behave when you ask to do something with that particular variable or value. Boolean, number, string, and object are some of the built-in types in JavaScript, and now that you know they exist we'll be able to talk about these types throughout the rest of the course and give you a deeper understanding of how to work with different types.

  18. Functions Let's look at another special type in JavaScript. This time I will console.log the typeof not just console, but console.log. Remember, this is the command we've been using to write something to the screen. And now when I save this program and run it, we'll see a new type in JavaScript, a type called function. Functions in JavaScript are fantastically powerful because they contain code that I can call from inside of my program. That's what we've been doing with console.log. It contains code inside of this function that knows how to write to the screen. It's a command. I can call it; I can pass it parameters and tell it what to write. And when I call it and invoke it using parentheses, that tells it to run and perform some work for me. Functions are so powerful in JavaScript. We'll spend the entire next module examining functions, but let me give you a preview because I can create my own functions. I could say var writeGreeting. So far it looks like any other variable declaration, but I'll say that this equals a function. So the keyword function in JavaScript is how you build a function. And then there's an open parenthesis and a close parenthesis and opening curly brace and a closing curly brace. Those curly braces denote the start and the end of the function definition. It's between that opening curly brace and closing curly brace where I can put my code. And I could put anything I want inside of here, multiple lines of code. So I could say console.log("Hello!"), and I could do that as many times as I want. And then, once I have function definition, I can call it from anywhere inside of my program. So I could say let's write a greeting and invoke it by using the parentheses. Now when we call console.log, console.log expects us to pass something to it, what do I want to write to the screen. WriteGreeting at the moment doesn't expect us to pass any data to it. So when I call it, I don't have to put anything inside of the parentheses. I just use them, and that's called invoking the function. And you see it does get invoked, and we say Hello! two times. But what's interesting about functions, number one, they can declare their own variables. So I could say message = "Hello!". And now instead of console.log("Hello!"), I could say console.log the message and console.log the message. And if I run the program now, it behaves the same. It still says Hello! twice, but now what it's really doing is writing the value of this variable, not the hard-coded string Hello! that I had here before. And then the other interesting part of a function is that you can pass it parameters. So when I call console.log, I have to pass it something to write to the screen, and writeGreeting I'm going to ask for you to pass me a name. You can think of things inside of the parentheses here as like variables that are defined for this function. Right now I have a variable called name. You could have multiple variables here, call them anything you want, name and x and y, but let's just go with a single parameter. You have to pass me a name, and what writeGreeting will do is put together a greeting "Hello, " + the name, so we expect to do some string concatenation here, write out that message so now when we call writeGreeting we should be passing in a name. Let's call writeGreeting for Scott, and let's call writeGreeting again with Allen. And then instead of writing that twice inside of writeGreeting I'll delete one line of code so we only call console.log once inside of writeGreeting. And now if I run the program, can you guess what it's going to say? Hello, Scott, and Hello, Allen. That's because we're invoking it twice passing a different parameter each time, and each time we invoke writeGreeting it's going to take that parameter as this name variable, append that to the string Hello, and write that message out on the screen. So this little demonstration barely scratches the surface of what functions can achieve in JavaScript, but we'll look at them again more closely in the next module. For now, just know that you can place code inside of a function. It's an actual data type in JavaScript. It's special. It's something that I can execute by using the name of the function and applying parentheses after the function name optionally passing in some data, and I can use it anywhere else in my program, which can be incredibly useful. We'll see why as we continue to move through this course.

  19. Summary In this module we took at look at variable declarations and learned a little bit more about the syntax of JavaScript. We saw how we could declare multiple variables with one var keyword and how to use and reassign those variables in the rest of the program. But perhaps more importantly we learned about data types in JavaScript. We saw a type for numbers, a type for strings, Boolean values of true and false, objects, and finally the function type. In order to build anything interesting in JavaScript, we really need to understand objects and functions, so the next module in this course will show you all the basics of working with functions.

  20. Learning To Program - Functions Introduction Hi. This is Scott Allen, and this module is about functions. We'll see how functions work, why we want to use functions, and continue programming with Node.js and JavaScript to run some experiments with functions.

  21. Roll The Dice The sample program for this module is going to simulate a roll of the dice. So I've created a new file in my text editor, it's called functions.js, but you can name it whatever you want, and what we're going to do is simulate the role of two six-sided die. So I have a variable for each die, and I'm going to paste in some code that will tell the user what they rolled for the first die, the second die, and then the total. And if we run this program, not surprisingly we do get back a 5 and a 3, so you rolled a total of an 8. But of course every time we run this program we always roll an 8, which doesn't make it very interesting to simulate the roll of the dice. What we need to do is introduce some randomness, and fortunately JavaScript has a random number generator. It's quite useful if you want to write a game. So what I'm going to do temporarily is comment out this code. We haven't talked about comments yet, but a comment in JavaScript, one way to create a comment is just to put a // somewhere in the code. And you can see this changes color. That's because that code is effectively not there anymore. It's commented out. It's not going to execute. Ostensibly, comments are here to add documentation to a program. So I might come in and I want to write something about how this program behaves, and that leaves a comment for other programmers. When they open this file they can see that and understand a little more about what the code is doing inside of here. But that's a comment, and all I really wanted to do was comment out these three lines so they don't appear in the output for the moment. And now what I will do is console.log a call to the function random on an object known as Math with a capital M. So I'm invoking a function here with the parentheses. I'm calling random. It's going to give me a random number. I'm going to take that value, that value is being returned to me, and immediately pass it into a log function on console, which will write it to the screen. So we're invoking two functions here on one line, and now if I run the program it looks like I'm getting different numbers each time, which is good. That's what random is supposed to do. But it's a random number between 0 and 1, which doesn't seem quite useful when you're trying to simulate the roll of dice. I need something that should ultimately produce a value between 2 and 12, so let's see if we can modify this a little bit. What happens if I did 6 * Math.random? Well, now every time I run it I do now get a value between 0 and 5. But fortunately as long as this value is between 0 and 5 I can apply another function here. So I want to take this result, let's say roll = 6 * Math.random. Or let me just call that a value and declare another variable roll, which is equal to Math.ceil(value). So, again, another function on the Math object. Some of these objects like console and Math they have multiple different functions that you can invoke. Ceil is short for ceiling. It says take whatever value you are given and round up, always round up to the next nearest integer. So if I have the value 5.9, that would round up to a 6. If I have the value 5.009, that would also round up to a 6. There's a round function that you could call if you wanted to go to the nearest integer. So the difference there would be 5.9 goes to 6, 5.4 goes to 5, so it gets rounded down. And there's a floor, which always looks for the nearest integer that is below this value, so the floor underneath of us. A 5.9 would always round down to a 5. I'm going to use ceil because I want to take a value like this 0.6 here and make sure it rounds up to a 1. We never want to roll less than a 1. And now I can output this roll. Save this file, and I should now see integer values between 1 and 6, which just doing a rough test here it looks like that's what I'm getting and they're fairly random. Now I wrote this in sort of a long hand way to just make sure that we understand what these functions are doing and how functions work. Math.random, random is a function. I invoke it by applying parentheses; it returns a value to me. I'll multiply it by 6 before I assign that to a variable. And ceiling, also a function that I can invoke. I give it a value, it inspects that, determines what integer is above that value, and gives me back something new possibly, puts that into roll, and now I can call a third function to output that to the screen, console.log. And if I wanted to, I could've place all of that code inside of here, so I could've said let's take 6 * Math.random, and then I want to take that value and pass it into Math.ceil. So I have to make sure I apply the parentheses correctly here because I want 6 * Math.random to execute and give a value to Math.ceil and then take that value and pass it to console.log. So three function invocations here on the same line of code, I don't need these other two lines of code, but it should produce the same results or at least a value between 1 and 6. It's not always going to be the same because we have some randomness now. And so if I really wanted to simulate the roll of dice, what I could do is take that expression and use it to initialize each of my variables. So now we have a value assigned to the first die and a value assigned to the second die. Let me uncomment these three lines of code and save the program and run it again. But before I do, something odd happened here in that all of my D's went to lowercase. It must've been a keystroke that I hit in Notepad++. And let's run this. So I rolled a 12, which is pretty rare, and then an 8 and an 8 and a 7. Those are more common when you roll two dice. A 4 and a 5, and hey there's another 12. We should stop there. But something that's a little subtle that's going on here with our function call is that functions can both take a value, and they can also return a value. So Math.random I don't have to pass anything to it. I don't have to put anything inside of these parentheses. All it does is return a value to me. I take that, multiply it by 6, and then Math.ceil it expects me to pass a value to it. So I take 6 * Math.random, I pass that into ceiling, ceiling inspects that value, and it returns something else. Math.ceil returns something that I can save and later output. Console.log, on the other hand, doesn't return anything. I don't need to save var result = console.log something. All I really want console.log to do is put something on the screen so there's no return, but it does also expect data. That's a parameter, what we call a parameter to console.log. So functions they can take 0 or 1 or more parameters, and they may or may not return a value. And if you're wondering how do I know if something takes a parameter or how many parameters does it take and what does it return, this is all available in documentation for Node.js, documentation for the JavaScript language. But for the functions that we use in this course I'll help you along and tell you what things take parameters and what things return values.

  22. Definitions In addition to calling functions that JavaScript already provides, functions like Math.random and console.log, there are also functions we can write ourselves. We did this briefly in the last module, but let's explore this more. First, why would you create your own function? There are several good reasons to create a function. Sometimes you create a function to make your code more readable, for instance this first line of code. It might take a while if you just opened this program and didn't view the previous clip as to what this line of code is doing. Math.ceil 6 * something, what am I trying to do? Well, I'm trying to simulate a die roll. So what if I actually had a function called getDieRoll? Now when I look at that line of code I get an idea instantly of what it's supposed to be doing. I'm not really concerned about the implementation of getDieRoll at this point. I just want to know that what I'm putting in firstDie is something that simulates the roll of a die. So it's a little more readable, and we put a lot of effort in programming into readability, trying to name things appropriately, give them meaning so that it's easy to come back into a program six months from now and fix something or change something. Another reason I might to function here is because I had previously, if I undo this change, duplicated code. Now this is just a simple piece one line of code, it's not a lot of code, but there is duplication. It's the exact same code that's on the line before it. And anytime you have duplicated code you should think to yourself can I replace this with a function because once I do have a function called getDieRoll I can replace all instances of that code with getDieRoll, and I essentially have that code packaged up inside of a function so I can reuse it anywhere in the rest of my program. Reusability is good. It's better than having the code duplicated everywhere throughout a program, so let's create that function. GetDieRoll is a variable that points to and then the function keyword. This is how you define a function keyword: Function keyword, open parenthesis, close parenthesis, open curly brace, closing curly brace, and then a semicolon. Everything between the opening curly brace and the closing curly brace is the code for that function. Right now there's no code inside of it, so it wouldn't do anything. But let's put a logging statement in here, console.log("rolling a die"). And we need to return something because when I invoke this function I expect to get a value back, in this case a value between 1 and 6, but I need to get a value back so that I can assign it to firstDie and still be able to simulate the roll of dice. So in JavaScript when you need to return something to the person that called you, you use the return keyword. So I could say return 4, and then we're not really doing anything random. We're always returning a 4. Or I could say return and the expression we had before, which was to use Math.random and then number 6 and Math.ceil to compute a number between 1 and 6. And now if I run this program, we'll get slightly different results because we have more output here. Rolling a die, rolling a die, 1, 6, and the total was a 7. But my program is a little bit different. I now have a function. So a couple things about this function. First of all, why wasn't this function invoked through something.whatever, like we always had to do console.log or Math.random? Well, those functions, random and log and ceiling, are attached to existing objects in JavaScript, the Math object, the console object. We'll talk more about objects in a later module and how you can attach functions to an object. The function we just wrote, getDieRoll, is not attached to an object, so I don't have to preface this with anything. I can just say getDieRoll and use parentheses, and it will return a number to me. The second thing about functions and about JavaScript that I've been implicit about to this point is that JavaScript does execute this program from the top down. In other words, it looks at line 1 and then line 2 and 3 and 4 and 5 and 6, and it does it in that order. And that's why we output the value on the firstDie before we output the value on the secondDie. And the last thing we output is the total roll because we're running from the top to the bottom. But when you have functions, things are just a little bit different, different in the sense that when JavaScript hits this first line of code it understands this to be a function definition, and it understands that the code that is inside of here does not execute immediately. Instead, that code is just stored away for later use. It's not until we invoke the function that JavaScript literally jumps in here to line 2, executes a console.log, does a return .Math call, and then we're back where we started where we call this function. So it will get that return value, put it in firstDie. We go to the next line of code on line 7, call that function again. That would jump us back into line 2 and then line 3, and then we'll come out and assign a value to secondDie. Just to make this a little more obvious, let me take the secondDie roll here and put it on line 11, which is after we log firstDie. See if you can guess the order of the output here. Will we see rolling a die twice like we did in a previous run, or will we see rolling a die and then some output and then rolling a die and some output? And the program says rolling a die, output, rolling a die, output, total. So you can see what functions allow us to do is share a block of code throughout the rest of the program. We can invoke that function from anywhere. It makes the program a little more readable. And it also slightly changes how our program executes. We're no longer executing lines 2 and 3 right away when this program starts running. Instead, those lines of code are inside of a function definition. We can call it wherever we want, and JavaScript will jump into that function, run all the code that's inside of it, and then jump back out.

  23. Parameters Currently our getDieRoll function has all of the information that it needs to compute the roll of a six-sided die. We don't need to pass any parameters, but a function can always accept parameters. Parameters to a function are specified in between these parentheses, and it's one of the beautiful things about functions. You can parameterize it. You can have it operate on data that a caller gives to that function, manipulate it, and optionally compute some result and return it. In this case, I've declared three variables, var1, var2, and var3, and then it would be up to the caller of the function to supply data for those variables so I could pass in a 1 and a 2 and a 3. Let me give you an example. Right now the only thing that getDieRoll can do is compute the result of a roll of a six-sided die. But what if I wanted to change that and roll different sized die? Then perhaps I could have a variable, dieSize, and instead of the hard-coded value of 6 here we'll use dieSize * Math.random. Now a caller can say yes I want a six-sided die. We'll roll a six-sided die twice. Now let's just clean up the code a little bit. I'm going to log our firstDie down here at the bottom, get the rolls here in the middle, and instead of console.log("rolling a die"), let me console.log(dieSize) and run this program. And you can see both times I called the function with a 6, and we rolled a 4. Now just because a function in JavaScript requires a parameter doesn't mean that a caller has to provide that parameter, so let's take a quick look at what happens when we don't pass a parameter on the first call to getDieRoll. In that case, the value of dieSize that appears inside of the function is undefined. You might remember undefined from the last module when we talked about variables. That's the value that we saw when we declared a variable, but never assigned anything to that variable. And that's essentially what is happening inside of our function. DieSize is very much like a variable that is declared for this function. I can use it anywhere inside of this function. But since the caller, when they invoked getDieRoll, didn't pass a value, dieSize by default has the value undefined. And then that messes up all of the mathematical operations that are taking place, and capital Na capital N stands for not a number. This is a situation that we could check on inside of getDieRoll. We could see if dieSize is undefined and do something differently if someone didn't pass us a value, but we'll look at that in the next module. For now, let me just show you that one of the reasons that functions are so great is because you can pass them parameters, and now the logic that we figured out to compute the roll of a die will now apply to 6-sided die or, in this case, 10-sided die. So in this game I rolled a 3 and 6 to produce a 9, an 8, a 6, a 10, an 8, and so forth.

  24. Scope Something that's very important to understand about JavaScript is variable scope. The scope of a variable is essentially where that variable is available. And in order to demonstrate scope, let me make a few changes to getDieRoll. First of all, I'm going to introduce a new variable inside of getDieRoll. It's going to be named result, and it's going to be assigned the result of Math.random * dieSize and everything else that we have there, and then we'll simply return result. So in a sense getDieRoll really has two variables available inside of this function. There's dieSize, and there's result. The question is are these variables like result and dieSize available outside of that function? So after we invoke getDieRoll a couple times, is it possible to console.log(result)? And the answer is, if I run the program, no, result is not defined. Result is what we would call a local variable, local because it was declared inside of a function, and so the scope of that variable is just inside the function body between the opening curly and the closing curly. And the same is true for dieSize. Because that's a parameter to getDieRoll, this dieSize variable is really only available inside of getDieRoll. So if I run the program, dieSize is not defined. But now let's define another function, get rid of this line of code that creates an error, and take a look at a different scenario. I'm just going to create a function called doWork. Or how about showResult? That's going to be a function that doesn't take any parameters, doesn't return any values, but I'm going to take the console.log statements down here that show all the results for the user, and I'm going to paste them inside of the function showResult. And so after we've computed the roll of the firstDie and the secondDie, what I'll do is invoke showResult. And the question is will showResult be able to see firstDie and secondDie? We know the reverse wasn't true. Outside of here I wasn't able to console.log a variable that was inside of a function, but can a function invoke something that's declared outside? And the answer is yes it can. So while dieSize and result are considered local variables that are only available inside of that function, firstDie and secondDie are considered global variables. They're not defined inside of a function or declared inside of a function, so they are available anywhere throughout the program, even inside of other functions. This also demonstrates, again, how JavaScript executes my program. You might wonder how I can console.log(firstDie) when firstDie isn't assigned until much later in the source code of the program. But remember, when JavaScript comes to line 6 it says here's a function definition. I'll store this code away for later use. It's not executing the code at that point. We get all the way down to line 12. That's when it really starts executing code inside of getDieRoll. Line 13 it calls getDieRoll again. Line 14, after we've assigned those two global variables, that's when we call showResult, that's when we can console.log firstDie and secondDie, and there are actually values in there that appear correctly. And showResult has access to those variables because they're declared outside of a function. They are global variables. They're available everywhere. Pretty much every programming language that you can work with has some definition of variable scope, where is that variable available. And many of those programming languages have the concept of local scope. That is, when I declare a variable inside of a function, that variable is only available inside of that function.

  25. Summary This concludes the module on functions where we learned how to define a function, return a value from a function, pass parameters to a function, and most importantly we saw how we could organize code with functions to make code more readable to give a block of code a name. And we also can avoid duplicating code in a program by putting duplicate code inside of a function and then calling it from other places in the program. We also learned an important lesson about variable scope. There are local variables that are defined inside a function and only available when you execute code inside the function, and then there are global variables that are defined outside a function and available everywhere. In the next module we'll see how to use variables and functions together again, but we'll also take a look at control flow and how to choose between two different paths of execution in a program.

  26. Learning To Program - Branch And Loop Introduction Hi. This is Scott Allen of Pluralsight, and in this module we're going to look at controlling the flow of execution in a program. This is where we check to see if something is true or false, like is a test score high enough to warrant the best grade in the class, or is it the lowest? We'll also be looking at looping in a program, which is a technique you can use to repeatedly execute a piece of code. That's something you might need to do if you need to compute the sum of a series of numbers. This and more awaits you in this module.

  27. If The Shoe Fits In the program for this module, we are again going to be rolling dice. So I started a new program in the editor. It's control.js, that's the source code file, and you'll notice that we have a function that we used in the last module, getDieRoll. You'll remember that simulates the roll of a die. So I could say something like roll = getDieRoll. And I have to specify the size of the die, so a six-sided die, and then I could console.log("You rolled a " + roll). And we'll output that into the window. So if I save this program and run it, you rolled a 1, you rolled a 4, you rolled a 4. And now let's say what we want to do is not just tell the user what they rolled, we want to evaluate that roll. We want to determine if it was a good roll or a bad roll. So let's say that a good roll would be any time you roll a five or greater. So if the user rolls a five or a six from this random dice generation, we'll say that's a great roll; otherwise, it's just a normal roll. We're going to do this using the if keyword in JavaScript. When you use the if keyword, you pass JavaScript an expression that it can evaluate to true or false. For instance, I could say if (1 > 0) then console.log("True"), and JavaScript will only execute this line of code if this expression evaluates to true. So anything between the opening curly brace and the closing curly brace, that only takes effect and executes if that expression returns true. So if I run the program now, of course it returns True. And if I said if (0 > 1), of course that is not true, that's false, so we won't have the True output in the program any longer. So coming back here if I wanted to evaluate this roll I could execute the roll first, and then inspect the roll and say if(roll > 4), that would be one way to write this. I could also say if(roll >= 5), then execute this code. And that's pretty much the expression that we want. I could say Great roll! inside of here. And now let's save this and see if we can get it to work. Hopefully we'll roll a 6 early, which we did. We rolled a 6. And there we rolled a 3, so that wasn't a great roll. And this is the essence of what we call branching logic inside of a computer program. If something is true, do this. If something is false, do this. Computer programs branch all the time. It's hard to imagine how many branches and if statements are in programs around the world. Reservation programs have to check if a seat is open. Games have to check if an object collided with another object. Stock trading algorithms have to check if a stock price is above a certain threshold. It really doesn't matter what type of program you'll be writing in the future. They pretty much all will have a lot of if statements and checks like this that operate on true and false values.

  28. Operators There are two types of operators that are commonly used inside of an if expression. The first type of operator is a comparison operator. That's what we're using right now, greater than or equal to. That's a comparison operator because it compares what's on the left hand side to what's on the right hand side. Is roll greater than or equal to 5? We could also check if roll is greater than 5, in other words you have to roll a 6, or we could check if roll is less than a 5, or we could check if roll is less than or equal to 5. You can also check if a roll is exactly equal to 5. That would be the only condition where we would print out Great roll! now. Or we can also say if roll is not equal to 5. So it's very important that you experiment around with some of these comparison operators just to make sure you know how they work and so that you can look at an if statement like if roll is not equal to 5 and be sure you understand what that means. But there's another type of operator that we also use inside of an if statement equally important. It's logical operators. Logical operators are used to combine true and false together in interesting ways. For instance, what if we went to say great roll only when the roll is a 2 or a 3? Well, we could certainly say if(roll >= 2), so then I'll chop off the 1 on the bottom. We won't say great roll when there's a 1, but we would also say great roll when it's a 4, 5, or 6. We only want to say great roll when there's a 2 or a 3. So the way I can express this logic is to use a logical operator known as the && operator. So this statement is about to say roll is greater than or equal to 2 and less than or equal to 3. So double ampersand is the and operator. It combines two Boolean values. Roll greater than or equal to 2 will return true or false. In this case for the if statement to pass and for us to say great roll, roll greater than or equal to 2 would have to return true, and roll less than or equal to 3 would also have to return true. So and combines those two together, and only when they're both true will it say yes the result is true. If either one of them are false or if both of them are false, the if statement doesn't go into the code that's inside of the if statement. And let's just try this out and see if we can get a 2 or a 3. So there's a 6, which was not good, a 4 is a not good, 6, 1, 4, 4. This will never happen of course. There we go. A 3 is a great roll. There's another logical operator, which is the or operator. So what if we wanted to say great roll only when roll was a 1 or a 6? So I could say roll == 1. That would take care of the 1 case. And now this logic on the right hand side isn't going to work. I don't want to compare to a 3. I want to compare to a 6. But this is an example of a statement that would always return false because both of these expressions cannot be true. One of them has to be false so the and will fail. But fortunately there's another logical operator, which is the or operator, so double pipes. On a typical keyboard that is the character on the slash key. You just have to hold down the Shift key in order to be able to type it. But or will return true if either side returns true, so if roll is equal to 1 or roll is equal to 6. And again, just to give this a test, hopefully it won't take too long, there's a 3 and there's a 1. Only the 1 was a great roll. These logical operators might seem a little bit confusing at first, but just think of reading them as English. Just make sure you know that this is or and this is and. So if someone comes to you and says I would like eggs or toast for breakfast, you know either one of those could be true, and you could make the person happy. Give them eggs or give them toast, and that would be the or operator. But if someone came and said I want eggs and toast, now you have to have both of them present. Both of them have to be true in order to make that person happy. To make sure you really have these down, try to make the following logic work in this program. Now there's one more logical operator to talk about, and that is the not operator. The not operator turns a true into a false and turns a false into a true. The way we could apply it here is to put not and then put additional parentheses around this inner expression to make sure we evaluate roll equals to 1 and roll equals to 6. So this expression will return true or false, and then not will flip it. So if the roll is a 1, and assuming this is an or statement inside of here, if the roll is a 1, this inner expression will return true, but the not operator will turn that into a false, so that's a way of saying a good roll has to be 2, 3, 4, or 5. I could save this really quickly and we could test it out. So a 3 is a great roll, a 1 is not a great roll now, and that's all because of the not operator, exclamation point or bang as some people call it. And we saw it before when we said not equal. So whenever you see the exclamation point in a programming language, many programming languages use an exclamation point as the not operator.

  29. If Variations Let's look at some of the exercises that I asked you to try in the last clip. First I asked you to try to print great roll only if roll was not equal to a 1. That one would be simple. We could just say roll != 1. I also asked you to print out great roll if roll was a 1, 2, or 3. Could've done that by saying roll < 4. Could've also done that by saying roll <= 3. Then I asked you to print out roll if roll was a 3, 4, or 5. We could say that roll >= 3 $$ roll <= 5. That would've worked for that scenario. And then I asked you to print out great roll if roll was a 1, 2, 5, or 6. One way to do that would be to say roll <= 2 || roll >= 5. That would work for that final scenario. And now just to make a couple other things clear about the if statement. I don't have to use the same variable in the if statement all the time. In other words, if I had two variables, roll1 and roll2, I could be checking those independently here. All we're really doing is writing an expression that has to evaluate to true or false. It doesn't matter what variables that we're using inside of here. It just so happens that I only have one variable, and I'm checking that one variable on both the left hand side and the right hand side. Secondly, let's go back to the scenario with the and condition where I was checking if roll is greater than or equal to 3 and roll is less than or equal to 5. There's another way to write this. I could write it like this with nested if statements. In other words, we only get here to line 9 if roll is greater than or equal to 3. And then I have another if statement here that says roll is less than or equal to 5. And I'm going to carefully indent the code to make it very clear what lines of code are inside of which if statement, so always indent your code inside of an if statement. Move it over two or four spaces or three spaces if you like three when you're inside of the curly braces for an if. That makes the code easier to read. And now I can glance at this and clearly see that we have to pass both of these if conditions to get to the console.log statement, so that's very much like using the and operator. We have to pass roll is greater than or equal to 3, and we have to pass roll is less than or equal to 5. Only then will we write great roll. Now my preferred way to write this would actually be with the and operator. So let me hit Ctrl+Z to undo these changes because I personally think that is easier to read than a nested if statement. A nested if statement can be a little bit complex, but you're going to run across them in programming, and they can be quite useful. But here's the way the program works right now. We only execute line 9 if that statement evaluates to true, and we always execute line 12. What if we wanted to execute line 9 if the statement evaluates to true and execute a different line of code if that statement evaluates to false? That's when you can use the else keyword in JavaScript. So an else attaches to a previous if, and we only execute what's inside of the if when the if expression evaluates to true, and we only execute what is inside of the else when the if statement evaluates to false. So I could say console.log("That was an ok roll"). So we're always going to print out one of these two messages, either great roll or that was an ok roll. We never print both out. And now if I save this program and run it, we should be able to see that. So a great roll is a 4; an ok roll was a 1. The random number generator is working with me now. And this is very much like the branching diagram that I showed you earlier. It's like a fork in the road. We either execute line 9 or we execute line 12, one or the other, not both, and it all depends on the if condition that is inside of the initial if. But we can also make this a little more complicated. Maybe we have a scenario where we want to evaluate three different conditions. This is a great roll. It's greater than or equal to 3 and less than or equal to 5. We could also have a terrible roll let's say if the roll is equal to 1, so else if(roll == 1) that's when we execute this part and have a final else condition down here at the bottom. And what we're building here is an if, else if, else condition. So I can say this is the condition for a great roll. If you roll a 1, that's a terrible roll, and otherwise we'll say you just had an ok roll. And now we have the logic structured so that we only say one of these three things. If we match this condition, we execute line 9, else if we match this condition we execute line 12, and if we didn't execute any of these previous if statements we'll always say at least that was an ok roll. So let's try the program out. A 1 is a terrible roll, a 4 is a great roll, so is a 5, so is a 4, a 1 of course is terrible, a 6 is just ok. So you can see how the logic is structured and how it is working right now. We essentially wanted to handle three different conditions inside of here. The final else condition without any if attached we always want that at the bottom. And now that you see how if and else if and else work, try out a few experiments on your own.

  30. While Do While When we talk about control flow in programming, we're talking about statements like if and else. They control what lines of code execute inside of our program. And that's one form of flow control. It allows you to branch. So line 9 only executes if the if expression in line 8 is true. But there's another form of flow control that allows you to jump around in a program a little bit, and we've seen that already. It's the function call. When I call getDieRoll, I jump into the getDieRoll function, execute lines 2 and 3, and then return back to line 6 and continue on down the program. In a way that's controlling the flow of the program too. And then there's another option for controlling the flow of a program, and that is looping. So a simple loop would look like this. I can say while(roll < 4) roll = getDieRoll(6). And if you interpret this statement as English, it means essentially what it says. It's saying while the roll is less than 4, roll the die again and assign that to the roll variable, the end result being that we should never see a roll down here that is going to be less than 4. We should never see a 1, 2, or 3 because when getDieRoll does return a 1 this while statement, as long as it keeps evaluating the expression inside to a true, it's going to keep looping, and it's going to keep executing line 9. And again, you can have as many lines of code inside of the curly braces as you like, so I could put a console.log statement in here just so we can see what we are rolling. And let's try to execute this program. So we rolled a 1, we threw that away, rolled it again and apparently got a 5, and there we rolled a 2 three times, and then we finally rolled a 5 and escaped from the while loop. So when roll was 5 this expression evaluated to false, and instead of going inside the while loop to line 9 we jumped out of the while loop, went to the bottom curly brace, and then continued on down the program at line 13. So a while loop is a way to conditionally execute these statements that are inside 0 or more times. So if roll immediately started off as a 5, we would've never executed the code inside here at all because the while statement, the expression inside would've returned false immediately. There's another form of loop that will always execute at least once, and that's the do while loop. So in a do while loop what you're telling JavaScript is that any code that I place inside of the curly braces I want that to execute at least once, but after it's executed check whatever expression I put inside of here, and if that expression returns true, continue in the loop again. And what I've just written here is an infinite loop. That's usually something bad to have in a computer program because I'm saying do while true meaning the program will never escape this loop, and the program will never stop executing, and that could pose a problem. But what I could do is say while(roll > 4) and inside of the loop do something to change the roll again. So we can get another die roll and log it, and we'll continue doing that while roll is greater than 4. So let me save this program and execute it once again. And with all the rolling and rerolling we eventually rolled a 1. That allowed the loop down here to escape. But really while and do while they're two variations on the same thing. I have some code that I want to execute. If I want that code to execute at least once no matter what else happens, I would put it in a do while loop. That way JavaScript will execute these two lines of code, then test this condition. If it returns true, we jump back up and do those two lines of code again. If that while expression returns false, we continue on in the program. If I have something that I might not want to execute at all, that's when I would use a while loop because JavaScript will test this condition first before it starts executing the code inside. So if roll is less than 4, we execute the code inside. But if roll is 5, we would never execute these two lines of code. And that's the primary difference between a while loop and a do while loop. Do you want to execute at least once, or do you want to test some condition before you execute the first time?

  31. For Loops Now we'll look at another kind of loop in JavaScript. It is the for loop. So I'm going to take some of this while statements outside of here and write a for loop. A for loop uses the for keyword. There are a couple of different syntaxes you can use in JavaScript when you write a for loop, but I'm going to show you one that uses three expressions after the for keyword and inside of parentheses. The first expression is what we call the initializer. It's an initializer because JavaScript will execute the first expression before the first semicolon here only one time when it starts the loop, so it's a place where you can initialize like a variable like i = 0. The second expression is known as the condition. What you need as the second expression is something that returns true or false, should we continue looping or not? So let's say I wanted to roll the dice 10 times. Then I might start i at 0 and loop while i is less than 10, so we'll do 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. That will be 10 times through the loop, and of course the loop body is whatever is inside of the curly braces. And this condition is evaluated each time before we go through the loop. So when we start off with i as 0 i will be less than 10, so we'll execute line 9, and then we'll loop back up to do the test again. But before the test runs there's this final expression, which is a piece of code that JavaScript will execute and before it does the test to see if it should go through the loop again. So basically what we're saying is we're saying start i at 0 and then execute the code inside of this for loop until i is less than 10, and each time through the loop increment i by one. You can actually implement a for loop as a while loop. It would look like this. I could say var i = 0 while (i < 10), do something inside of here, and then before you go back to the start and test for i is less than 10 increment i by 1. That would produce the same result. But the for loop is usually a slightly more compact syntax to do the same thing. So let's say each time through this loop what we'll do is console.log the value of the roll variable and then compute a new roll by calling getDieRoll passing in a 6. So let's save this and execute the program, and what you'll see is that we output 10 numbers, and then the last roll, the roll of 3 is something that we actually evaluate. But I could always go back and change this for loop just to loop for i is less than 5. Then we would only have five numbers. And I could also do something like var i = 0; i < roll. Instead of rerolling the die, let's just output a star for each dot that would be on the die. In other words, when I roll a 1, we get one dot; when I roll a 6, we get six dots. And so for, while, and do while, those are the three primary looping constructs for JavaScript.

  32. Arrays Revisited Finally, I need to tell you about arrays. Arrays are something we saw before in the second module. We looked at process.argv, and I told you that was an array of items. It was the items that the user typed on the command line to launch Node and execute a program and optionally pass in some additional things. You'll remember we took some input from the user and then acted on that. An array is a collection, and you can put nearly anything into an array in JavaScript. You can put in strings, you can put in numbers, you can put in objects. And nearly every programming language has the concept of an array or at least some collection where you can store multiple things and then operate on that as a group. If I were to define my own array, I could create a variable called things. And then the syntax in JavaScript to create an array is square brackets and a semicolon at the end of the line of course as always. And inside the square brackets you can put things delimited with commas, so I could put numbers like 1, 2, and 3. But you can put anything in a JavaScript array, so I could also put a string like pizza. And then if I wanted to write out everything inside the array, I would have to execute some code inside of a loop and execute code for each item in the array, and the key there being for each item. So I could say for(var i = 0; i < things.length. So a very important concept of arrays is that they have a length. That's a property on an array. A property is something that you can walk up to with a dot operator and say give me the length. Much like log is a function on the console object, I can walk up to it with the dot object and then invoke it by applying parentheses afterwards. Length I don't need to invoke it like a function. It's just a property, so it gives me back a value instantly. Things.length I want to go from 0 to less than things.length and increment i each time. That way I can say console.log(things. Now things itself is the array. I don't want to log the entire array. I want to log a specific item in that array. And the way that you index into the array or get a specific item out is by using square brackets. So I could say things sub i is the way that would read. Give me the first time through the loop. Give me the thing in position 0. Arrays in JavaScript will start at position 0, and then there's 1 and 2 and 3 inside of this particular example. So pizza is in things sub 3. And just to make that clear, let me come out here at the top before we start looping and log things sub 3. And now when I run this program you should be able to guess what this is going to print. I hope it prints pizza, 1, 2, 3 pizza, pizza for the first console.log, and it'll print pizza again at the end because we're looping through the entire array. So with that program being saved, let me try to execute it. And there we got pizza, 1, 2, 3, pizza. And if I wanted to do something with an existing array like argv, I could get rid of things here. And let's say for i = 0 i < process.argv.length. So now I'm getting the argv property of process, which is an array, argv is, and then length of the argv array looping through that, and I will write out process.argv sub i. Let's save that real quick and run this. And you can see what it wrote out was node, that was the first item in argv, and then essentially control.js, but with the full name of the file including the path to the file. And there were two items in that particular one. Let me run it again, and this time I'll type in pizza, fish, toast, and eggs. That would make for a very strange meal. But we get node control.js pizza, fish, toast, and eggs, so I'm looping through argv printing out everything inside. So the key here is understanding how to work with arrays. We'll work with arrays again in the future and keep coming back to this concept and loop through some arrays and build arrays and put things into arrays. But the for loop can be very useful when working with an array because you can go from 0, that's usually the first thing in the array, to less than the array .length. And then inside of that for loop you can just have the code that does whatever you need to do with that array, sum up the numbers that are in the array, print out the strings that are in the array, and so forth. We're also looking at something else implicitly here, something that we'll cover in a little more depth in the next module, and that is that objects can be quite complex. I can have an object in JavaScript, something called process, and that process object can have properties attached to it, properties that are arrays or that return string values. It can also have functions attached to it like console.log is something I can walk up to invoke. But when you have a property, something like argv, which is an array, it itself can also have functions attached on other properties. So process.argv.length is sort of walking down through a chain of objects ultimately to get the length property of that particular array. And again, that's something that we'll come back and explore when we talk about objects in JavaScript.

  33. Summary In this module we looked at code for branching and looping. We saw the while loop where you use an expression at the top of a loop to control how many times the loop executes, and the do while loop where the expression at the bottom of the loop controls the number of loops so you'll always execute the code inside at least once before you test the loop condition. We also saw if and else if to test Boolean conditions and looked at comparison operators like greater than and less than and logical operators like and and or. Finally, we used a for loop. We used a for loop to print out an asterisk for each number that was in the roll. We also looped through an array and the process.argv array with the command line arguments to our program. In the next module we'll be using functions, loops, and arrays again, but the primary focus will be on objects.

  34. Learning To Program - Objects Introduction Hi. This is Scott Allen with Pluralsight, and this module is all about objects. There are many modern programming languages that have the concept of objects including the JavaScript language we've been working with. And JavaScript offers a number of different techniques for creating objects, but we're going to stick with one easy approach that will teach us some of the fundamentals of working in a language that supports objects.

  35. Why Objects? First, let's talk a bit about the concept of an object. Objects allow you to group related data and behavior into a container, a container we call an object. Not all languages support objects, but many do, and nearly all languages have some concept of grouping or organizing pieces of a program to make it more manageable, and that's one reason to use objects, to organize. We've been using objects already in this course, and I've pointed them out a few times. One object we've been using a lot is the console object. Console is a grouping of functions related to interacting with the command line window where we run Node.js. I can say things like console.log("Hello"), and that line of code prints Hello to the output window. Log is what we call a member of console. To access the log member, I use the period or dot operator and say console.log. And since log is a function, I can then use parentheses to invoke it. There are other functions on the console object that we haven't looked at, functions like warn and error and still others that I haven't listed here, but give them a try on your own. Warn and error are also functions to output text to the window, so I can say console.error and pass in an error message. The important part, though, is that since all these functions like log and warn and error they all output text to the command window, so it's nice to have them grouped inside of a single object like console. If they were not part of the console object, if they were just functions I could call by saying log with no console dot in front, then that could still work, but I might have hundreds and thousands of functions in a complex program. And if I couldn't organize those functions into groups and keep them separated, it would be mentally difficult to work inside the program. Objects allow us to think in terms of real things that we can walk up to and code and interact with. And since objects have a name, our brain is able to better keep track of what is going on. I might have an object to represent a bank account or a shopping cart or a spaceship in a game. The shopping cart object might have members that allow me to add items to the cart for checkout, and the shopping cart object will keep track of what is added. And that's another important concept of objects. They can be more than just functions. They can have state, which is the data that an object stores. We've seen an example of that with the process object. Process has an argv member, and that's an array of everything the user typed in the command window to launch Node. We can access that array; we can retrieve values from it. That's a piece of state, and these pieces of state that an object exposes they're often called properties or attributes of the object. Another property of the process object is the title property. That contains the title of the window that Node is running inside of. To access title I can use the dot operator, but it's not a function so I don't need to invoke it. When I use the dot, the title property just automatically returns the title of the window. Let's look at a few of these concepts inside the REPL.

  36. Objects In the REPL Let's go into the Node REPL. And you might remember the REPL from the introduction of this course. The REPL is set up to read what I type, evaluate what I type, print out the result of evaluating that expression, and then loop back to read something new. So inside of here you can try all sorts of JavaScript expressions like is 2 greater than 3? No, that's false. Is 3 greater than 2? Yes, that's true. And the REPL will always try to print out something. So, for instance, if I give it a string, it echoes back that string. If I assign something to a new variable called message, it will then inspect message and echo back what's inside of message. I can also give it objects. So I could say tell me about console, and it essentially gives me a dump of what is inside console. You can see there are a number of different functions in here including log, info, warn, and error that we talked about before. And if I say dear console what is log, it can tell that's a function. And a function is something that I can invoke with parentheses, and that's different from process.argv. That's not a function, that's a property on the process, and so the REPL has just dumped out the contents of argv. There's only a single item inside of it, and that's the string Node. That's what we used to start this program. I could ask for process.argv sub 0, and that will give me just the string, not the containing array, but the first element that inside of that array. And of course process also has a title. That's another property on the process. This is literally the title of this window that we're running inside of, Node.js command prompt - node. But many properties you can read the property just by saying dot and the property name, so that's reading the title property of the process. Most properties you can also set. So I could say process.title = "Hello!", and that's setting that property. And that changes the title of this window. I could also set title to the message variable that we declared earlier. And again, we changed the title of the window. But not everything on process is a property. If we dump out process, we can see there are all sorts of different functions and properties on this object including a function called exit. Can you guess what that will do when I invoke it? It exits the process. So console is a grouping of things that are related to the output window; process is a grouping of things that are related to this Node process that is executing on my computer.

  37. Build Your Own Now that we've seen how objects behave in the REPL, let's take a look at how we can define our own objects. Now there are many different ways to create objects in JavaScript, but I'm going to show you a very simple approach. I'll declare a variable called die and assign it a new empty object. So like many other things in JavaScript, an opening curly brace and a closing curly brace define some sort of scope. In this case it's not a function, it's not an if block, just the curly braces on their own with a semicolon at the end defines an object, in this case an empty object. There's nothing inside of it, but it will be an object nonetheless. That's known as the object literal syntax in JavaScript. It's the easiest way to create an object. And now that we have that, let's actually console.log(die) just to see what this looks like. So I've put all this code inside of a new file called program.js. Obviously I'm keeping around the getDieRoll function. We're going to work with that a little bit later. But with the code in place and this new file saved, let me go out and run program.js, and we essentially dump die, which is an empty object. So we don't see anything inside of the curlys, but let's give die a size. I could say size: 4, and so the syntax that you use inside of this object literal is to say name, colon, value where that value can be a hard-coded number like 4, it could be a function definition, we'll get to all that. But right now my die will have a single member on it, a property called size. And of course I could console.log(die.size) just like we could console.log, process.title. I could also change the size, so die.size = 10 and then copy this line of code to log the die.size again. Let's save this file. I would expect to see a 4 and then a 10, and indeed that is what I get, a 4 and then a 10 because we're changing die.size. And that's an example of a property. And you can generally have as many properties on an object as you need. So when you add additional members to an object using this syntax, use a comma. There are no semicolons at the end of these lines, which can be a little bit confusing. It's just name, colon, value, comma. And I could also have something called count and save this file and run it again. And now you can see die has two properties on it, size and count. But we can also add functions to this. So let me create a function called roll that is a member of die. This is almost just like declaring variables, but instead of the equal sign you use the colon inside the object literal. So I'm saying roll is a member of die, and roll is a function. And like every other function we've written, you have an opening curly brace and closing curly brace that defines the code that is inside of that function. And for the implementation of this I could say let's take this code from getDieRoll, paste it in here, carefully indent it so I can clearly see what is inside of that roll function. And now we no longer need getDieRoll, but we still do need a dieSize parameter at the moment. We'll come back to this. And now what I should be able to do is I could console.log(die.roll. So die.roll with a 6; pass that to console.log. What we should output now are some random die rolls except I have an unexpected identifier. And the reason I have an unexpected identifier is because I forgot a comma here. So after each entry in the object literal make sure to use a comma. You don't need a comma after the last one, but also make sure you're not using a semicolon. Save this file. Let's try it one more time. There I can see a die has a size, a count, and a roll. And when I invoke roll I get a 4, sometimes a 2, sometimes a 5, and once again a 5.

  38. This Responsibility Now that we've built our own object, let's give it some responsibilities. I say responsibilities because our objects often have a purpose. In this example, the purpose of a die is to represent a die that you can roll, but it can also have responsibilities like remembering the size of the die. Is it a six-sided or ten-sided or twenty-sided die? And we could also give it the responsibility for keeping track of the total number of rolls. So let's see how to do this. I'm going to make a few changes. First of all, I do not want to pass the size of the die every time I call roll. Instead, what I would like to do is initialize that and say something like die.size = 10, so it's a ten-sided die. And then I want to be able to roll that die a few times, so let me copy and paste and rearrange some code. We'll roll the die three times, and then I want to be able to console.log(die.totalRolls), and that can be a simple property on the object. Now if I try this right now, obviously we're going to have some difficultly because we're no longer passing in the size of the die or the roll function to use, so it gets a parameter value of undefined, and that messes up the math calculations, so we get not a number. We've seen that before. You can also see that die.totalRolls is undefined. And that's what happens when you try to access a property on an object that doesn't exist. You'll get back undefined. So let's fix up our die so that this program will work correctly. First of all, instead of count, let's create a property totalRolls and initialize that to 0. That'll be the starting value for totalRolls. And the size of the die, let's initialize that to 6, so it's a six-sided die by default. And now I no longer want to use dieSize, a function parameter, so I'm going to remove that from the function. Instead, I want to access size here inside of the Math.ceil operation. And the way I do that is not by just saying size. I have to use a magic word in JavaScript. I have to use this. Now this can be a bit tricky in JavaScript, but here's the way to think about it. This is an implicit variable that you can use in a number of different places. And when I call die.roll and I'm inside of the roll function, this will point to the die object. In other words, this.size should be referencing this property on the die object itself. And in fact the this keyword, because this is a reserved word in the JavaScript language, the this keyword is required in this scenario in order to be able to reach the size variable. So let's run the program quickly. We roll a 6, a 4, and a 9, but totalRolls is 0 because the object is not correctly calculating the number of total rolls. We need to increment that value every time we do a roll. But the this keyword appears to be working because we're saying this.size and we're getting back a 10, and that's why all of our rolls are between 1 and 10. What happens if I do not use the this keyword, if I just say size * Math.random? In that case the program misbehaves, it crashes, it errors out because JavaScript does not find size. It's looking for a variable defined as size. There is no variable defined as size. Instead, there's a property on this object, on this object, so I need to say this.size. And any time you're inside of a function on an object and you want to refer to another member of that object like totalRolls or size, you have to use the this keyword. So to increment totalRolls, I cannot just say totalRolls += 1. What I have to say is this.totalRolls += 1. That makes sure that this line of code will find this particular property. And now let me save the program again and run it, and we did three rolls. This.totalRolls returned 3. And let's just make that a little more explicit by adding some text to the output and save this program one more time. And now you can see that it's properly tracking the total number of rolls.

  39. Splitting Up And now let's do something just a little more advanced. I want to give you a glimpse of some of the techniques a bigger application will use to structure itself to manage complexity because big programs are complex, but we have techniques we can use to reduce and hide complexity to make programs easier to work with. One of those techniques is to use multiple source code files to build an application because if I stay inside of this program.js file and I just keep writing code until there are thousands of line of code, then it becomes difficult to find anything. But if I break up 1000 lines of code into 5 or 10 or 20 files, I have a better chance of finding what I need and understanding the different parts of the program because files have names, and I can give a file a meaningful name, and then files can be arranged into directories on my file system, the hard drive. And directories can also have names, and they can group my files together so I can see an even bigger picture of the application. So just like objects are a grouping of properties and functions, files can organize our code too. Each file can contain the definition of an object or multiple objects. And there is no definitive limit on how much code you put into a file or how many files you can use to build and application. Remember, the goal is to make things easier, make things easy to find. In our application, once I have the die object defined, I don't need to keep the object in program.js. Program.js, the code inside of here, it's going to be the consumer of the die object. It's going to use the die object to simulate rolls and write results to the console, but that's separate from the definition of die itself. Program.js will be about what the program needs to produce. I just want program.js to use objects defined in other files, and that makes program.js itself a little bit simpler. So this die object I'm going to select it and cut it out of this program. So now program.js is just about configuring the die, rolling the die, console.logging the die rolls. I'll take that die code, create a new file, paste it in here, and let's save this file as. Let's call it dice.js because it might eventually contain other bits of code related to dice and rolling dice and keeping score in a game of dice. And back in program.js I still want to use die, so in order to do this my intention is to use dice.js, and that's something Node has to know about. It won't just pick up random files and use them together. I have to be very explicit in my programming and tell Node that I require dice.js. I require some other source code for the program to function correctly. Right now if I save program.js and we run it again, now I'll have an error, and the program stops and halts and crashes. It says die is not defined. I need to tell Node about the other code that I need. So the syntax to do this is to invoke a function that is always available inside of a Node program. It's a function named require. It almost means literally I require this other thing. And I have to describe what I require using a string, so the syntax here will be ./dice. This tells Node to look for something called dice. Behind the scenes what Node will really be looking for and what it will find is dice.js, that other file where die is defined, but I don't have to use the .js part of the name in require, just dice. Node will infer the .js part and will find the right file. The ./ in front of the string is telling Node to look in the same directory as the program.js file because both program.js and dice.js they're in the same directory together, so ./ is the proper syntax to use in this case. In a later module we'll see a slightly different syntax. And now the require function will force Node to find dice.js. If it doesn't find it, it will throw an error. It will, when if finds it, load and execute that file, and dice.js will define the die object when it executes. But it won't be available to use inside of the program just yet because everything that Node loads from a file it's going to hide by default. When I require something, everything inside of that file is going to be hidden by default. In other words, just using require here doesn't give me access to everything inside of dice.js. If I save this program again and run it, we still get the error die is not defined. Yes, Node has found the file because it hasn't given me an error about not being able to find anything related to dice. It did find the file, but we still don't have access to die. Using require is not like a literal include of the source code program where I would just take the contents of dice.js and include them or paste them into program.js. It works a little bit differently than that in Node with require. This is because programmers like to hide as much as possible inside a file so complexity doesn't leak out, things that other people don't have to know about. We're not just going to expose everything from inside of a file. We only expose what we choose to expose, the pieces that other people need to use. Inside of dice.js I have to explicitly tell Node what I want to make available to other files that are requiring this file. The syntax to do that in Node is to work with an object called exports. This is another one of those objects like console and process that will automatically be available to you and running in Node. And the name is very descriptive of what the object does. Anything that you add to exports will be exported for other people to use when they require the file. So I'll give my exports object a property called game and point it to my die object. What exactly is going on here? Exports is a JavaScript object, and I can walk up to any object in JavaScript and just give it a new property. For instance, I could walk up to the die object and just give it a name property by saying die.name = "A name." That will create a new property on die called name. Previously die didn't have a name, but if I did do a console.log die.name at this point, we'd see the string value that I assigned. This is very similar to adding a name up here. That would have the same effect, but I'm just doing it later in the source code. Outside of this object literal syntax I'm adding the property here. Well, exports is also an object in JavaScript, and I can walk up and give it new properties like a game property that references my die. I picked the name game, but you could also call it die or foo or any name that you want. As it stands, exports.game and die, they'll both be the same object. And anything that's in my exports will now be available to any file that requires dice.js. But in order to gain access to these exports, what I need to do when I call require is assign the result of that function call to a variable. So let me declare a local variable called dice and set that equal to require.("/dice".) And this variable dice will now point to the exports object, so it will have all the same things that I added to exports in the other file. Let's see if I can make this a little bit clearer. I'm going to select all these lines and use Notepad++ to comment everything out so we get rid of all the other output, and let's just do a console.log(dice). And I'm going to make sure all my files are saved, and we're going to come in and run the program. And you can see when I do a console.log(dice) we get an object that has something called game, and that game points to something that has size, totalRolls, and a roll function. Well, that's the die. We just happened to call it game when I did the exports. I could also call it game.die = die. And if I save this file and rerun the program, now we have exports.die. And that's what I could use inside of program.js to get a hold of this. And you can add as many things as you want to exports. So I could also say something like exports.name = "My dice exports." And if I save this file again and we run the program, now we have two properties coming through in exports. One property points to my die, and that allows me to do things like roll a die. And then I also have the name property, which is the piece I just threw in there at the end. But let's see if we can actually make use of this now. Over in program.js I still don't have a die. Let me uncomment all this code. I still don't have a die just yet. That is part of the exports in dice. So one way I could do this is to declare another local variable die = dice.die. In other words, give me just this object out of the exports, and I'll work with that. And now I should be able to save this program and run it, and now we're back to rolling die and keeping track of the total number of rolls. So there are a couple important concepts here. The most important bigger concept is that nearly every programming language and environment has a mechanism that allows you to package up code and use that code from some other project or some other application or file. In Node this is done through require, and it's done through exports. And nearly every language also has some mechanism that allows you to hide the details you don't want other people to see. That's what we call encapsulation in programming. It's a very important concept and something we'll look at more in the next course with the Python programming language. We will be using require and exports in later modules of this course, and you'll see some of the interesting things that you can do by requiring code that other people have written. That allows us to easily build things like a web server that can serve up web pages, and we'll see an example of that later, but this was a quick introduction to exports and require with Node.js.

  40. Summary In this module we took a closer look at objects, and we created our own object. We gave the object properties to hold data or state, and we gave the object functions that can invoke. We saw how to use the this keyword inside an object's function so that the function can refer to data inside the object. And we also learned how to package code into different source code files and then use the Node.js require feature to pull the code and objects from other files into a program. We did this using require and exports. One of the beautiful things about require is that we can require other people's code and build on what they've already written. There are thousands of JavaScript libraries out in the world that we can require and then build on top of. We'll do this in the next module when we learn about testing our code.

  41. Learning To Program - Tests Introduction Hi. This is Scott Allen, and this module is a look at testing JavaScript code. When we write code for a program, we need to see if the code is working properly. We all know that bugs and software are everywhere. It can be a challenge to write a program that works 100% correctly the first time. The process of checking your program to see if it works and produces the right numbers and doesn't crash, it's called testing. There are all sorts of techniques that you can use to test your code. For simple programs, you can just run the program after you add some code or make changes to see if it produces the right results. In this module I want to introduce you to automated testing. Automated testing can run your program again and again and automatically make some checks to see if it's working correctly. This is just a basic introduction to testing to give you an idea of what many professional developers will do to improve the quality of the software they create. I hope it helps you in the future by making you aware of these practices and also allows you to try out testing on your own to make sure some complicated pieces of code are working correctly.

  42. Setting Up The program I want to write for this module is going to be a grade book. That is, I want something written in JavaScript that I can walk up to and code and say here's a score, here's a test score, here's another test score, here's a bunch of scores, now compute a grade for the class for me. Is the grade an A, which means the student did excellent, or is the grade a B or a C, and we'll talk about the different categorization of grades here in a bit. But this program is going to involve a few more moving pieces, so I want to set up a directory structure that lets me organize my source code. So first I am going to the command prompt, and I'm going to make a directory for a gradeBook. And then I'll cd or change directory into that gradeBook directory, and inside of here I will make a directory that will hold my tests for the program, and I'll make a directory called lib, L-I-B, so that's short for library. When programmers talk about libraries of code, that's repositories where you can place source code and reuse it inside of a program. So what I'm picturing is that inside of this lib directory that will have some sort of grade book file or source code or object that I can interact with, and I'm going to use that gradeBook both inside of the tests, but also inside of my program that actually executes and computes the scores for me. My tests will verify that the gradeBook is working correctly. And there's one more piece that we have to set up. I'm about to use something known as the Node package manager. So if I just search for node package manager, we'll come to a site called npmjs.org. NPM is short for Node Packaged Modules. So a module, very much like a library, it's source code that someone has already written and tested and debugged, and they're making that code available to me to use. One of the beautiful things about using Node is there are so many open source projects out there that you can use from a Node program to do things like build a website, build a program that saves information into a database or into files on the file system, just a huge number of components. So you can see NPM lists that there are over 30,000 packages in NPM, that's 30,000 different things that you can potentially download and use in your program, and there's almost a million downloads every day from NPM. And the package that we want to use is a package called nodeunit. Nodeunit is a unit testing project. If I go into the search results and click on this, I can get more details about nodeunit including the most important detail, which is how to install it. You can see if I want to use nodeunit to run tests that I'm writing, because that's the ultimate goal here, I need a program that will run my test and automatically tell me if my program is working or not. That's what nodeunit will do. That's the example that I'm going to walk you through. In order to use nodeunit, though, I first have to install it with this utility called NPM. Before you type that command, though, let me show you exactly what you have to do. I want to type npm install -g nodeunit. And once I do that, NPM goes off, and it starts downloading modules, downloading packages, downloading zip files, downloading whatever it needs to download onto my computer so that I can use nodeunit. It downloads all this stuff, extracts it, installs it in the correct location. Really all I should need to do is type npm install -g nodeunit, and we'll come back as soon as this has finished downloading. Alright, now nodeunit has installed, and I should now, from the command line, be able to type not just node, but also nodeunit. Now I haven't told nodeunit what to do. All I've done is typed nodeunit, and you can see it comes back with a message that says files required. That is what nodeunit expects me to do as it expects me to point it to a file that contains some tests that I want to run or a folder, a directory full of tests. Just like when we type node space program.js to run the code that's inside of program.js, nodeunit expects us to pass something that says here's the code to run, here's the test that I want you to exercise. So ultimately what we'll do is we'll type in nodeunit tests because we'll have all of our tests inside of JavaScript files in that tests folder. And if I do that, nodeunit now comes back and says okay I looked in that folder, I basically didn't find any tests inside of there, so everything worked. It comes out with a nice green OK. It only took 1 ms to run because there was nothing there. There were 0 assertions. What you typically do with a testing tool is you write assertions about your program. So you say if I give my program these pieces of data, this grade and this grade and this grade, this is the score that should come out. Now assert that is correct, and nodeunit will tell you if that assertion worked or not. And then at this point we're up and running with the basic tools that we need. We have nodeunit; we have a directory structure. Now all we need to do is start writing some tests and writing some code to make those tests pass.

  43. First Test This module is going to build heavily on a few of the things that we learned about in the last module including things like exports and require. When we write a test, it's going to be in the tests folder. It's going to require a file that's in the lib folder. I'll create that file first. That'll be the gradeBook file. Inside of the gradeBook file I want to have some object that represents a gradeBook, so let me create the new empty object using JavaScript's object literal syntax that we learned about. And then let's create some exports because it is exports, you'll remember, that make things inside of this file available to the rest of the world. So I could say something like exports.book = gradeBook, and now book will be available to anyone that does a require on this file. Let me save this. I'm going to save it in our gradeBook directory in the lib folder that I created, and I'll call it, let's call it grades.js. That means inside of a test file I can require this and be able to access book. Let me go ahead and create that test file, so I'll say give me a new File. Let me go ahead and save it as a js file so I get some syntax highlighting. So in the tests directory let me create gradeTests.js. It's inside of here where I could say something like var book = require. And now I have to specify the path to grades.js. I have to specify a path from the test directory, so--is a way of saying go up one directory from the test hub directory. And then going to the lib directory, and then look for something called grades. I don't have to specify .js at the end remember, just grades, so that syntax will go up from the test directory, into the lib/grades directory, find grades.js, load it up, and grab the exports. And since what I exported for the gradeBook was essentially something called book, let me go ahead inside of here and say let's assign that exported book into a local variable called book here. And that'll be enough to write my first test. That's everything I need to interact with the book from the tests that I put inside of gradeTest.js. And now, perhaps you'll find this strange, but I actually want to write the test first. Before I put anything inside of gradeBook, I'm going to write a test that describes what I want the gradeBook to do, which I think is an interesting mental exercise because it allows you to think about what you're trying to program and have a test in place to tell you when it works. Obviously if you write the test before you implement the code inside of the thing you're trying to test, the test is going to fail, but that's perfectly reasonable, that's perfectly okay. So the way you write a test or expose a test to nodeunit is through exports also. Anything that I export from a test file, nodeunit is going to look at it and try to interact with it like a test. So let me create an exports, but using a slightly different syntax than we had before. The first thing that I can think that I want to do with a gradeBook is have the ability to add a new grade to it, to be able to walk up to the object and say here, here's a new grade for you to store. Later on you'll compute something interesting about it, but for now I just want you to store it. And the way I do that with nodeunit and the exports is to use this funny syntax with the square brackets that we usually associate with an array, but that's also a way to add something to the export to object. So one way to do that in JavaScript is to say exports dot and then some identifier. Another way is to use square brackets and a string. And the interesting thing about this approach is that the thing that you add into the object can have spaces in it, so can add new grade. That's something in the exports object, something nodeunit will be able to look at. And that's going to be a function. So tests are functions that nodeunit invokes, and it will be able to tell me if the test passed or not. In order to do that I need to pass in a parameter, a test object that nodeunit will provide. And with that test object I can write asserts, so I can say things like test.done to let nodeunit know that the test is finished. And let's just save this file and save grades and run nodeunit again to see what it says. You can see it ran the function can add new grade, but there are still 0 assertions. So technically everything is still passing, but we haven't really asserted anything. So let's do this. Let's walk up to the book and tell it to add a grade, a grade that is a score of 90. And then I might expect that once I add a grade I should be able to walk up to the book and get a count of grades, and it can tell me how many grades are inside of the gradeBook. And I would expect at this point for the count to equal 1. So this line of code on line 7 is an assertion. It's saying that count something that was computed by interacting with the code that I'm about to write inside of the gradeBook produced a specific result, in this case a 1. If it didn't produce a 1, something is wrong with gradeBook. If it did produce a 1, the test will pass, and I know my program is working in that respect. So let me save that file, we'll run nodeunit tests, and of course we get a failure. Nodeunit will try to help you track down problems. So this test has failed. I can tell that because of the bright red text says 1/1 assertions failed. Also, if I scroll up a bit, I can see that nodeunit test failed inside of the test can add new grade, and in fact if failed on line 4. If we look at line 4, that's where we call addGrade, and obviously the problem here is that addGrade does not exist, so let's try to fix that. Let's go into grades.js and give it some members. AddGrade is a function, hopefully you remember this syntax from the last module on objects, addGrade is a function is that you can invoke. I expect you to pass a parameter, which is the newGrade that you want the gradeBook to store. And now where will the gradeBook keep that? Well, let's also add a member called _grades that points to currently an empty array. So why did I start this one off with an underscore? Because in JavaScript there's sort of convention, a sort of agreement between programmers that when you have a member of an object that starts with an underscore that's really only for the object itself to use. Someone outside the object writing code outside of this object like in a test or in the program, they shouldn't manipulate _grades at all. They should pretend it's not there. It's only for the gradeBook to use. And what I want the gradeBook to do is to be able to store this newGrade in this array because arrays in JavaScript they're resizable. You can add new things to them, you can remove things from them, in addition to iterating through them as we did before. Let's go ahead and add something to the array, but I'm going to have a subtle bug here. See if you can pick it up. I'm going to say grades.push(newGrade). So push is a function that's available on every array. It allows you to push something new into the array. So I'm saying take this newGrade number, push it into the array, so it should now be stored as a member of that array. And if I save this file and we run this again, we'll find that we fail again, but this time the failure is a little bit different. Underscore grades is not defined. That was the bug I was telling you about. Do you remember why this is from the last module? It's because I need to use the this keyword to access another member of this object, this._grades.push(newGrade). And now I can save this and run the test again. And this is what's great about tests. Right now there's only one test, but eventually we could have 5 tests or 10 tests or 1000 tests, and every time I run all the tests they can tell me exactly what in my program is working and what's not working. It can catch all these little errors. So the error now there's no getCountOfGrades. Remember that's what we're trying to use here to find out how many grades the gradeBook has stored, so let's add that as another function. I'm just going to space things out a little bit so they're easier to read. But getCountOfGrades is a function, and this function will simply return this._grades. Dot length is the way to get the length of the array. So let's save that file, run our test one more time, and this time nodeunit can tell us that our single test has now passed. We have the ability to store a grade in the gradeBook, and the gradeBook can keep track of how many grades are stored, at least so far.

  44. Second Test Now that we've had some success with the first test, let's think about other things that we want the gradeBook to do. Given a gradeBook, I might want to add multiple grades into it and have it compute the average grade, so I'll have another exports that will add another test to this file. So you can have as many tests inside of a test file as you want. This one I'll call can average grades. And as always that equals a function that takes a test. And I'm just going to clean things up a little bit by making sure each function ends with a semicolon and space things out so they look properly formatted. Obviously I didn't need the semicolon, the test had run and passed, but I like to have the semicolon there. JavaScript is kind of flexible that way. And now if I want to see if the book can compute an average grade, I'd probably want to add a few grades into the gradeBook, so let's add a grade of 100, let's add a grade of 50, and I would expect if I asked the book to compute an average given those two scores, 100 and 50, that it would come back and tell me that average would be 75. That's what I expect the gradeBook to produce, and then of course test.done to let nodeunit know that this test is finished. So given that test, of course if I run nodeunit right now, it's going to fail because getAverage doesn't exist. Can add new grade still exists, it's still passing, but can average grades is failing because getAverage doesn't exist. And now give it a try. See if you can implement getAverage. What you'll have to do before I show you how to do it is loop through the grades array using a for loop, and for each item in the array you'll need to add the item into some sort of running total. And after you've computed the total, which is the sum of all the grades in the array, compute the average by dividing that total by the number of items that are in the array. Give it a try yourself. And now let me show you how I would implement this. Of course I would add a new member to the gradeBook called getAverage, that's going to be a function, and inside of here I will need a for loop. So we need to go to each item that's in the array; I'll need some sort of variable that will index into the array. I'll call it i. That's quite common in for loops to use a variable called i when you're just trying to loop through an array. You can think of i as standing for integer because it's an integer that will go 0, 1, 2, 3, 4 up to the length of the array, or you could also think of it as i for index, so indexing into the array, but it needs to start at 0. That's the beginning of the array. Remember, the second expression in a for statement is when to stop, so I want this loop to keep going while i is less than this._grades.length. And then the third expression in a for loop is what to do after each iteration of a loop. I need to increment i, so i += 1, and that means I should go 0, 1, 2, 3, 4 up until it reaches the array length. And that's my for loop. Inside of the loop what I need to do is look at this._grades sub i and pull that value out and add it to a total. I don't have anywhere to store the total yet. That can just be a variable inside of this function, so var total = 0. And each time through the loop I'll look at grades sub i and add that to the total, so total += this._grades sub i. That would be everything I need to compute the total. And now to compute the average given that total, just need to return total / this._grades.length. That's the number of items in the array. Let me save this file, make sure the test is saved, and run nodeunit again. And it's still failing. So let me scroll up and see that inside of can average grades, which is still failing, there is an AssertionError. So an AssertionError would tell me that a test.equal or a test.not equal or a test.okay has failed. And it's trying to tell me why it failed. It failed because 80 is not equal to 75. In other words, if we look at the test, it's saying that the average that the gradeBook computed for some reason wasn't 80 even though I expected it to be a 75. And indeed it should be a 75. If I take 100 plus 50 and divide it by 2, that should come out to be a 75, so I'm really curious how this got to be an 80. Now we could look at the code that we wrote for getAverage and look at it all day long trying to spot some sort of bug, but the problem actually is not inside of getAverage. The problem is actually inside of our tests, and it's something to be careful with when you write tests. Let's see if you can figure it out. To make it easier, let me take the second test, can average grades, cut it, and paste it into the file as the first test. So now can average grades comes first, and can add new grade comes second. These tests should be able to run in any order, so it shouldn't matter what order I put them in here, just trying to demonstrate a problem. Let me run nodeunit again. We still have a failure. If I scroll up, the failure is different. Now apparently can average grades has worked. It did compute the correct average, but can add new grade is failing. You can see the AssertionError. Three is equal to 1. That's the problem. Three is not equal to 1, so the assertion failed and tells me that my program has a problem. And so let me ask you can you think of what is going on here? Why would the gradeBook have three grades when I reach this line of code? And maybe you suspected this already, but we're using the same gradeBook inside of each test, so there's exactly one gradeBook here. And when the first test runs we add two grades into the gradeBook, and when the second test runs we add a third grade into the gradeBook. And although I could come down here and say yes I expect the count to equal three at this point, sometimes that just makes tests more complicated when you keep changing things inside of each test and you have this test rely on changes that were made in a previous test. That's generally bad, and that's why I want to keep count equal to 1. I want to be able to look at a test and see everything that happened to a book and say yes there's only one grade inside of here. And in order to do that I'm going to use a feature in nodeunit that allows me to set up the environment for each test. Nearly every testing framework has a feature like this, and nodeunit is no exception. With nodeunit, what I can do is export something called setUp. And remember, JavaScript is a case-sensitive language, so this has to be called setUp with a lowercase S and an uppercase U. And when nodeunit sees something in the exports called setUp, it will take that function that you've assigned to setUp, and it will invoke this function before every test. And so a setUp with a testing framework is typically something that you use to put things into a pristine state. In our case, I want setUp to be able to clear out any state in the book, clear out any grades, that we're always starting with a fresh empty gradeBook. And the way I could do that is to add a new method to the book. Let's call it reset. So before every test I want to call book.reset, and then this callback parameter that comes as part of the setUp, nodeunit will automatically pass that in when it sees something called setUp. That is a function that I just have to invoke at the bottom of the setUp to let nodeunit know this is finished. No more complicated than that. So now what should happen when I save this file is that when I run nodeunit it will invoke setUp and reset the book. Then it will invoke can average grades. When that's finished, it will call setUp again and reset the gradeBook and then call can add new grade. So what I'm hoping to see is that both the tests pass because the book will be in a pristine reset condition before we come into can add new grade. But the one thing I need to add to make sure this works is a reset method to the book. So let me go into grades.js and add one more member. Reset is a function that simply needs to clear out any existing grades, which is easy to do. I can say this._grades = an empty array again. That's the easy way to do it. So let me save this file, make sure the test is saved, run nodeunit, and I now have two passing tests. I can average grades; I can add grades. And now this is the beauty of tests. I have some tests around me that can tell if my library is working correctly, and I can continue to make changes to the gradeBook and add new features, and the tests I've written are always there to help me pinpoint problems. They also helped me design. They let me think of features I wanted the gradeBook to have and implement those features in small pieces. Keep trying tests as you learn programming because writing tests is a great way to learn more about programming and also program design and even the problem that you're trying to solve. Tests can help with that too.

  45. An Average Program Let me show you something that you can do with the gradeBook now. It's a variation on the you try exercise that I had at the end of the last clip. I created a file program.js, and I saved this file in the gradeBook directory, so not in the test directory, not in the lib directory, in the gradeBook directory itself. And what program.js does is first it goes out and it does a require on the gradeBook. So ./lib meaning from this current directory that I'm in, go into the lib directory, look for something called grades, and pull out the gradeBook. Put it into a variable called book. And now what I will do is loop through process.argv. Remember, that's the arguments that are passed on the command line. So if I type node program.js 70 80 90 75 93, those are the grades that I want to average. And I could type as many as I want here because what we'll do is we'll loop starting at i = 2 because remember node is argv sub 0, program.js is argv sub 1, so the grades start at process.argv sub 2, so this will be 2, 3, 4, 5, and 6. We will loop until we reach the end of the argv array incrementing i each time, and again starting at 2 because that's where the numbers are. And then using i we'll look inside of argv, pull out that number, and we'll parse it into an integer. We covered parseInt in a previous module. It's a way to take some user input and make sure it's transformed into an integer, into a number instead of treating it like a string, and then we'll tell the gradeBook to add that as a grade. And at the end of the program we'll simply write out the average score. So let me save program.js, we'll run it with those values, and you can see the average here was an 81.6.

  46. Summary In this module we've used a few of the things that we've learned in previous modules like how to build objects, how to use exports, we brought in some code with require, and ultimately we built a gradeBook and wrote tests for that gradeBook. Testing software can be difficult at times. It can be tough to figure out what test you want to write and how to test something, but I wanted to introduce you to the topic to let you know just how important testing can be in software. Stick with it and try writing tests. It can help you be a better programmer.

  47. Learning To Program - Final Introduction Hi. This is Scott Allen, and this is the final module in this first course of Learning To Program. In this module we'll enhance the gradeBook from the last module and then take the gradeBook to the web using Node and a web browser.

  48. Letter Grade One of the features we wanted for our gradeBook that we talked about in the last module is the ability to compute a letter grade. Letter grades are common here in the states. Everyone does them a little differently, but let's say for our gradeBook that if the average of all the grades is a 90 or greater then the letter grade is an A. That's the best grade that you can have. It means the student has achieved excellence on all the tests and assignments. An average from 80 to less than 90 is a B, and the 70's is a C, and the 60's is a D, and a failing grade is an F. That's anything below a 60. Let me paste in a test here in gradeTests. We're still working with the same files that we were in the last module, but this is a test to describe some of that functionality. I want to see if the gradeBook can compute a letter grade of A. So given a 100 and a 90 as the two scores, the average should be 95, which is in the A range. If I ask the gradeBook to give me a letter grade for these two, I would expect that the result should be an A. And so here's an assertion on line 14 that says please assert that the result is an A. And if it is, the test passes. If it doesn't, there's something wrong with the program. Go ahead and see if you can implement getLetterGrade to make the test pass. I'm going to go ahead and implement getLetterGrade, and I think I'll do it in a way that hopefully it would compute the correct letter for all the different scenarios. So getLetterGrade is a function, and inside of here the first thing we'll need to do is compute the average. And we already have a function on this object that can do that, so let me declare a local variable and assign to it the result of calling getAverage. And that's a member of this object, so I need to use a this in front of it. And now it's time to figure out what letter should be assigned given that average, and there are all sorts of different approaches that you could use for this. You could start off by saying okay if the average is less than 60, I'll return an F. That would be one way to do this. And then I could have additional if checks down here to evaluate if it's less than 70 and 80 and 90. Or I could reverse this. The wrong way to do this would be to say if average is greater than 60 return a D because if the average is a 62, yes a 62 should be a D, but if the average is a 90, that's also greater than 60, and we would return a D in that case too. And we don't want to return a D for a 92. A 92 should be an A. And remember, the return statement, this exits the function at this point. That literally jumps back out of the function to the caller, so we wouldn't execute any other code that would be inside the function once we hit that return statement. But let me implement this this way. If the average is greater than or equal to 90, in that case we'll return an A; else if the average is greater than or equal to 80, in that case we'll return a B; else if the average is greater than or equal to 70, we'll return a C; else if the average is greater than or equal to 60, that would be a D. And if we haven't assigned a grade as yet and we've reached this point of the function, that must mean that the average is less than 60. That's the only way that we could reach line 24. And if the average is less than 60, then unfortunately we have to assign a letter grade of F. So this is one way to implement the function, and let's give it a try for our test that's trying to see if the gradeBook can correctly compute what an A grade should look like. So let me run you a nodeunit tests, and it looks like we have a success.

  49. ExpressJS Finally, I want to show you something a little more advanced because I would feel it was a lost opportunity if I didn't show you one of the areas where Node is popular, and that's the area of building websites because Node.js can function as a web server and will let you build websites and web applications. Anything from writing your own blog engine to the family photo album, any type of website you can think up can be built with Node. One popular way to build websites with Node is to use a package, a library named Express or Express.js as some will call it. Express.js is simple to install and simple to use to build a basic website. I'm not going to go into too many details in this module, just enough to get your feet wet. And if you're interested, there are more Pluralsight videos on using Node and Express, as well as books and websites and all sorts of materials. To get started with Express, I just need to install it. And, once again, we can go to npm, the Node package manager that gets installed with Node, and we can ask npm to install express. And npm will go out and look at where it can download Express and all of the other libraries that Express might depend on. It will go out, automatically download those to my machine, and install them for me to use. We'll come back as soon as this process is finished. Now the Express setup is finished. Let's come back into our program, which currently just runs on the console, and we're going to turn it into a web server that we can interact with through a web browser. So I'll delete everything except the first line, which is getting the grades library, that's our gradeBook, we'll be using that later, but we're also going to be using Express. And the way to bring in Express since it is an installed module is simply to put require("express"). There's no dot or dot dot slash required for this one. It's not something that's local to the application. It's an installed module. Node will know how to go out and find that. And then we're going to create a variable called app, short for application, and what Express exports is essentially a function that I can invoke. And what I get back is an application, and I can tell that application that I want to listen for connections. In this case I'll choose port 3000. So if you're not familiar with networking, every computer has communication ports, and when you go out on the internet and connect to a server using a web browser or an FTP client or Windows Explorer to look and see what's available on a computer as a network share you're always connecting to a specific port. Usually when you launch a web browser you're connecting to another computer on port 80. That's the default port for web communications. And we're building a web server, but we're not going to listen on port 80. Sometimes that causes some conflicts. We're going to listen on port 3000. So I'm telling the application hook yourself up to port 3000 on this computer, and if there are any connections made over the network to that port try to respond to them. And now this program is going to behave a little bit differently than it did in the past. We're not going to just run this and it's going to exit right away. We're going to run this, and it's going to stay running until we tell it to quit because we have an application that is actively listening to a port. And it will do that forever unless we tell it to stop or the machine reboots or loses power. But I will write out something from a console here and say the server is ready and it's up and listening. And that's all I need to do at this point just to get a very basic web server up and running. It's not going to do anything. It's not going to have any interesting responses to a web browser, but it is going to be running. I should be able to type node program.js. You can see the server is ready here in the background. Windows has popped up a security alert saying essentially something is trying to open up a port on the network to listen for incoming connections. Are you sure you want to allow this? And I'll say yes. Let's roll the dice and allow access. And now what I should be able to do is use any web browser and try to get to localhost as an alias for this machine. Port 3000, that's the port that Node is listening on. And what we get back from Express is a response that says sorry but you've requested the root of this website, essentially the root path, and I don't know how to respond to that because we haven't told Express what to do. So let me tell Express what to do. I'm going to exit the server by hitting Ctrl+C, that will stop the server, and come back into the program and tell the application how to behave in certain circumstances. So I'm going to tell the application when someone tries to get the root of the website they just type in localhost:3000 or the name of this machine :3000. I want you to respond in a certain way. And the way I tell it to respond is to write a function that takes two parameters. There's a request parameter, and there's a response parameter, req request, res for response. Request is the incoming request, what the web browser is sending me. I can inspect the request to find out what type of browser it is and other information like that. And then res is short for response. That's what do I want to respond to the web browser with. So I will write this function to say that when someone requests the root of this website say Hello, World in the browser. And let me just fix up the syntax here. I need to put a parenthesis here because we're inside of a function call, get, and we're writing a function. So essentially what this block of code is telling Express is that when someone tries to get the root of the website execute this function, which will tell you how to process that. In this case we're going to process it by sending a response that's simply Hello, World! And now I should be able to save program.js. Let's run the web server again and now come back to my web browser and refresh, and there's Hello, World!

  50. Web Grades Now that we have a basic web server up and running, what I'd like to be able to do is this: I'd like to be able to go to a different URL, a different address here in the browser like /grade, and I would like Express to respond to that. But there's more. I would like to be able to pass in parameters to that URL to Express and have it use the gradeBook to evaluate them. The way you pass parameters in a URL is to add what's known as a query string. You've probably seen query strings if you've done any web browsing. A query string is anything that follows the question mark in the address bar of your browser. So if I type in ?grades=100,90,80,95, then grades is a query string, and it contains the value 100, 90, 80, 95. I'd like to be able to send that to Express and have it compute an average grade and a letter score using the gradeBook that we wrote earlier, so let's do that. First, the way I respond to /grade is to add another app.get. So I'm saying if someone tries to get /grade and I don't include the query string here, that's really not part of the URL, just /grade, what I want you to do is execute this function, a function that takes a request and a response, and it's going to pull those parameters out and compute the grade. So the first thing I'll need to know are what are the grades that are in the query string. Fortunately Express makes this very easy. The request object will have a query property available on it, and that query property will have whatever items that you have in the query string. Here we have just one. It's called grades. Grades will be the string 100, 90, 80, 95. So if I just ask for request.query.grades, that is what I would get. I would get a string, 100,90,80,95. But if I take one more step and call split on that string, what split will do is go through a string and break it up into smaller pieces wherever it sees this character, a comma. But I could have anything inside of there. So I could have split on a space. Wherever you see a space, break that string up. And what it will do is turn a string into an array of items. In other words, if grades was the string 1, 2, and 3 and I told it to .split on a comma, what that would produce is an array 1, 2, and 3, an array with three items in it. That's what split will do, very useful. And now what I'd like to do, I have an array of the grades. I'm going to need to loop through it, so a for loop that we've written before for i = 0. I has to remain less than grades.length, and each time through the loop we will increment i by 1. And now we have the ability to add things into the gradeBook. Remember with our gradeBook we can tell it to add a grade, that should be a number; we can tell it to get an average; and we can tell it to get a count of grades, but that might not be useful here. We can also tell it to reset. You might find that useful if you play around with this web application enough, but for right now we just want to call addGrade on the book, so add a grade. The grade I want to add is grades sub i. But there's one more important step here. Grades sub i is going to be a string because we took a string and we split it into an array, so we have an array of strings. We're pulling one item out, but we need to make sure we parse that into an integer. We used that in a previous module. Please take the string, make sure that it comes out as an integer value, and at that point that should be everything that we need to put our grades into the gradeBook. So now let's compute an average. That is simply book.getAverage, so book.getAverage, and then we'll find out what the letter score is, the letter grade, so book.getLetterGrade. I will just copy that and paste it here to avoid typos. And now we should be able to send a response. So I can say res.send("Your average is " + the average, that's string concatenation + " grade " + letter) and the response. And now let me save this file and come back to the server which is currently running. I'll hit Ctrl+C to stop it again, relaunch it with the new code, so node program.js. The server is ready. Let me come into the web browser and refresh this, and it looks like this worked correctly. The average is a 91.25, and that is an A. And now what I've demonstrated here is a very, very simple use of Express.js to build a web server and a website, and you can take this much, much further. And with the skills that we've learned in this course so far, the ability to write objects and functions and invoke functions and set properties and also use require and exports, you'll have enough basic knowledge to play around a little more with Express. Of course there's a lot more to Express than just the JavaScript. There are all the other technologies that go into building a website, things like HTML and CSS and some other things you might've heard of. But if you're interested, you can always poke around on the Express site and see how to build bigger applications or also look at the other videos on Pluralsight which cover Node.js and Express.

  51. Summary This concludes the first course on learning to program. I hope I was able to teach you some interesting topics using Node and JavaScript. If you want to continue to see what you can do with JavaScript, try out some more examples with Node and Express.js. Or maybe you want to write JavaScript for web pages in the browser. Wherever you want to go, JavaScript is usually available. There are now databases where you store and query objects using JavaScript. You can write Windows 8 applications with JavaScript. You can even work in the latest version of Microsoft Office using JavaScript in places like Excel worksheets. Just remember the most important part of learning to program is to write code and write programs. The more you write, the more you learn, so grab an idea, and start writing some code.