 Hi, my name is Bob Tabor and in this course you'll learn about JavaScript the language. This course is aimed at those who are absolute beginners. So beginners to JavaScript and frankly, given that we're going to discuss some very basic things like if statements and for loops, it's really designed for those who are beginners to programming in general. So if you know some HTML and some CSS and you want to learn JavaScript, awesome. You're in the right place. So there's nothing specific to Windows in this course. The tools that I use will be free and available in Mac and Linux as well. So you should be able to follow along no matter which operating system you're comfortable with using. Now my background is really not all that important but in case you're curious, I am a software developer by day and by night I run a website called Developer University or DevU. You can visit me at www.devu.com. Occasionally Microsoft invites me to create courses and what you see here is a collaboration between myself and the good folks at Microsoft Virtual Academy. I've been creating courses like this since 2004 and I created a very successful version of a JavaScript course way back in 2011. It's been viewed millions of times and I've got a lot of very positive feedback about it. This is a rewrite, a complete rewrite of that course because frankly JavaScript has changed dramatically in the what, six or seven years since I originally recorded that course. And so if you're already a software developer coming from a different programming language, just kind of to pick back up what I said earlier, this might move a little bit slow for you. It just wasn't designed with you in mind. There might be some other courses that can move you through the introductory material a little bit more quickly than what I plan on, than the pace that I plan to take with this course. And my focus is the JavaScript language, the pure language, not web development necessarily. Although we will discuss JavaScript in the context of the web browser at the very end of this course, but it felt like teaching JavaScript and how it's implemented in the web browser clouded the discussion of JavaScript, the language itself. So we're going to be writing what amounts to console or rather command line style applications to isolate JavaScript, the language as purely and simply as possible without clouding it with a bunch of HTML and CSS and things like that. We're going to discuss the language. We'll discuss popular patterns that have emerged from the JavaScript development community to help overcome some of the challenges associated with working with such a highly dynamic language, such a unique language and sometimes kind of a quirky language. The last time that I recorded the course about JavaScript way back in 2011, the course actually had a fairly long shelf life and so much has changed with JavaScript since then that necessitated that I actually play catch up and kind of learned some of the new features that were added because I wasn't keeping my skill set up. That's how quickly things change out from under you if you're not careful. If you know anything about JavaScript, you know that the community around JavaScript is moving extremely quickly. It's the most popular programming language, not just in the web browser where there are hundreds of JavaScript frameworks and libraries that you can leverage in your own applications, but it's also becoming one of the most popular languages for server side web development, meaning the code that actually runs on a web server that can perform business logic, that can interact with data storage databases and other styles of data storage. And we're not going to talk about any of those topics in depth per se, but it is important to know that it all starts with a basic understanding of the things that we will discuss in this course, the absolute basics of JavaScript. So since this course may have a long shelf life, it's important to know that some of the features of the latest version of JavaScript, which I will be covering in this course, may not yet be implemented in all web browsers, depending on when you view this course. And then you have to take into account that some of the people viewing your website, for example, might be using very old web browsers. And so you have to keep that in account as well. So I'm going to make two general suggestions and I'm going to try to remind you about these at the very end. There are still people on the internet that are viewing web pages with browsers that were created 10 years ago. So clearly in these cases, the newer features of JavaScript, many of which we'll discuss in this course, will not be available in those browsers and your JavaScript won't even work in those web browsers. So you have a choice at that point. You can go one of two routes. You can either attempt to write your code in such a way that it is as friendly as possible to those older web browsers. Or you can use a tool which will transpile your JavaScript code that you write using the latest features of JavaScript. It'll transpile it back into a version of JavaScript that is compatible with all web browsers, even those that were built 10 years ago. And it uses a combination of techniques to accomplish this. We're not going to get into any of those. But if you want to take the first tact, if you want to be careful with the JavaScript that you write and only use those original features, I guess you can say, of JavaScript or the early features of JavaScript. There's a website for you. You want to take a look at this website called Can I Use? And so we can take a look at maybe one of the newer features of JavaScript, the Let Keyword. I'll type it in here in the search box Can I Use and it will show us the Let Keyword, gives a quick description of what it is. And then it will show for the current versions of each of the web browsers, whether it's supported or not. You can see that the Let Keyword does have wide adoption across all modern web browsers with a couple of exceptions. Now if you want to go ahead and use the absolute latest version of JavaScript, and then take that second tact where you transpile your code so that it's backwards compatible with as many versions of the various web browsers as possible, then you want to check out a website like and a tool actually called BabbelJS. So you can find it at babbeljs.io. And it will, again, use a combination of techniques to take your code. And you can see some of this little animation that's on the page right now. You can actually use this to type in some code here and see how it converts it into the older style JavaScript. And I'm not going to cover how to use Babbel in this course, but you should know upfront that writing JavaScript for web browsers requires that you give some careful thought to how your JavaScript will ultimately be consumed and who your targets are. And that definitely means that you're gonna have to take into consideration the fact that some people will be using older web browsers. The writing JavaScript that will run on a web server using a framework like node.js is a bit easier because, well, you're gonna have some upfront knowledge about where that code will ultimately be executed. But this is not a course specifically about node.js either. Even though we're going to use node.js as a lightweight means of executing these little tiny JavaScript examples that we're gonna create throughout this course. So you're gonna learn enough about node.js to be able to write a simple tiny application, but it won't do anything cool like serve up a web page. However, I'm sure there are other courses here on Microsoft Virtual Academy and elsewhere that will help you kind of take that next step. So the game plan for this course is to start in the very next video by installing the tools that you'll need to get started. And then we're gonna start with the absolute ABCs of JavaScript and programming in general. And I encourage you to follow along by typing in the code that I type in the video and typing it yourself is the absolute best way to learn. Starts to develop muscle memory. You'll have many of those aha moments where you realize, I see how these two things are related. You can hear it and that's one thing, but to type it in and to see it on your own computer working is something entirely different. I highly recommend that you become an active learner by typing in the code yourself. But I encourage you also to pause and rewind the video as many times as you need. This isn't a race. You don't consume these kinds of videos the same way you would watch a TV show, a movie or a YouTube video. If something's not clear to you, don't just let it go in one ear and out the other and worry and say, I'll figure it out later. No, stop down and figure it out now because you never know. It might be something foundational you'll need to know in the next lesson and the next lesson. But by the end of this course you're gonna be well positioned to move on to a more advanced JavaScript course to learn how to use modern client frameworks like React and View and Angular. Or you'll be well positioned to learn more about server side framework libraries, frameworks and libraries like node.js and express.js and others. But no matter what you're gonna have a great foundation to build on. If something I say doesn't make sense, again, I can't stress this enough. Seek out other sources online. And you're gonna ultimately want to know something from me. I've recorded enough of these courses. I know the questions that are already coming. You're gonna ask me if there's a book that goes along with this course that I could recommend. And I'm sorry, I don't really have a specific recommendation. Honestly, my recommendation is that you exhaust the dozens, if not hundreds of JavaScript online resources where you can simply use them for free and find them in an instant if you wanna get more explanation about any given idea that's covered in this course. Okay, so let's go ahead and get started. I wanna encourage you to take your time. Don't feel overwhelmed. Stick with JavaScript, stick with this course, and you're gonna be well rewarded, I promise. It'll be more difficult than playing a video game, then watching a movie or reading a book, but I promise you, you're gonna wind up enjoying it even more than any of those things. Even if I wasn't paid to write code, I would do it because it's fun. It's mentally challenging and you get this rush whenever you write code and you see it working and you're like, wow, this is awesome. So I'm glad you're gonna get an opportunity to do that. It's the most fun you're gonna have on a computer, I promise. And you'll wind up enjoying it. So stick with it and I'll try to encourage you along the way. All right, so we'll get started in the next video. See you there, thanks. All right, so let's get started. We're gonna install the tools that we're gonna need for the remainder of this course. Fortunately, we don't need a lot and everything is free. And everything I show you will work regardless of which operating system you currently have installed. So regardless of whether you're using Windows, Mac, or Linux, everything I show you will be available for those platforms. The first thing we're gonna need is a web browser. I'm pretty sure you already have one of those installed, any will do. I would probably recommend that you either use Microsoft Edge or you use Google Chrome. The second tool that we're gonna need to install is Node. It is the JavaScript runtime. It's what will actually execute the code that we write. And we'll talk about that more in just a moment. And then we're gonna need an authoring tool, something where we can actually type the code in. Now in the past, I've used Notepad to actually demonstrate. Cuz I didn't wanna recommend one tool over the other. But then Microsoft came out with Visual Studio Code. It's available on all three platforms. So it's also available for free. So no matter what you're using, you should be able to download it and follow along. Now you may already have a favorite tool for creating web pages and so forth. Feel free to use that. I'm not gonna do anything that's so Visual Studio Code specific that it will exclude you. Please follow along no matter what tool you prefer. But let me put in a good plug for Visual Studio Code. I've been using it pretty much as one of my exclusive tools in my full time job for the last three months. And it's really good. So I highly recommend it. Let's get started. We're gonna need Node. And you may already have Node installed. So let's just see if you do or not. Let's go and in Windows, I'm gonna open up a command prompt. And I'm gonna type in node-v. If I had Node installed, it would display the version of Node that I currently have installed. I don't have Node installed on this computer. So I get an error message. That's good. So to begin, we're going to go to Node.js. I'm gonna type, there we go, nodejs.org. And again, regardless of which operating system you're using, you should be presented with an opportunity to download either the supported version or the current version which has the latest features. You don't need that. Just use the LTS version, which is recommended for most users. As long as you're using the version that I'm using or greater, we should always be in sync. Again, we're not gonna use any really advanced features of Node, so this shouldn't really matter much. I'm gonna go ahead and run it, run the installer here. What you see next, depending on which operating system you're using, you may see something a little bit different than what I see on screen. But hopefully you've installed things frequently enough that you can work your way through it. So here we have the Node.js setup wizard. And I'll just walk my way through, agree to the license. I'm going to pick a place on my hard drive to install this. There are some options. I'm not going to really do much of anything, but I do wanna make sure that in Windows that this is added to my path. This will make sure that Node is available in any directory of my hard drive. So when I type in Node V from anywhere in my command prompt, it'll pop up, okay? So just make sure that everything is selected and you'll be fine. It's not that large. Next, I'm gonna have to agree to Windows UAC. You may see something different here on the Mac or Linux. I'm gonna go ahead and agree to that little security prompt. And it only takes a minute or two to install Node and then we'll move on. But basically, Node in a nutshell is the V8 JavaScript engine that they ripped out of Chrome. They added some tooling around it to support things for like HTTP, working with requests and responses and with the file system. And they created one of the most robust web server tools that is available today. And many large applications are using Node currently to host their applications. We're not gonna use it for that. We're gonna use it for something much more mundane, which is to really just write out little text messages to a console window as we get started. Then we'll graduate on and use it in web pages much later in this course. All right, so I should have it installed, right? So I come over here and it still says it's not installed. I'm gonna have to reboot my computer. So let's pause, I'm gonna pause the recording of the video right here. I'm gonna reboot and then when I come back in, we should be able to move on from there. All right, so I've rebooted. Let's open up a command prompt, type in Node-V and I can see the version number. So we're successful. The next step is to install Visual Studio Code. Visual Studio Code is different than the full version of Visual Studio. So Visual Studio Community, Professional, or Enterprise. Visual Studio Code is a lighter weight code editor mainly used for web development, but I know people that use it to develop C-sharp applications and other type of applications where you can use the command line tools to compile your code and things of that nature. That's not something I would ever wanna do. It's great for web development and that's what we're gonna use it for. For authoring our JavaScript files and then executing Node commands in a built-in little command window, command prompt, like we see there. Again, available for all operating systems. You just go to code.visualstudio.com. It should be able to detect which operating system you're currently using and it gives you a download option for that. All right, and we're gonna go ahead and run it in place. Again, Windows UAC prompts me to make sure that I am authorized to install it. We get to the code setup wizard. I'm gonna go ahead and accept the agreement and we're gonna work our way through the defaults. Sure, and you can see that we can also add Visual Studio Code to the path, which will become available after restart. I don't need that necessarily for this course, but hey, you know, it doesn't hurt. In fact, let's go ahead and use it for everything here. That's up to you. You can read those options and choose what you want, but for my purposes, this will work just great. And we'll see throughout this course some of the things that Visual Studio Code will do for us as we're typing our code. Simple things like code coloring and code completion, managing our files, giving us an environment to execute command line tools like the Node command line tool. And there are many things like that, IntelliSense, others, that will give us the tools to hopefully allow us to author our JavaScript code accurately. So let's go ahead and launch it. And let's just do what I call a quick smoke test. And we don't need get for this course. I'm just gonna hit close on that. So what we'll do is go to the Explorer. It's the little icon in the upper left-hand corner here. Let me kind of pull this out and make this a little bit sized a little bit more nicely here. Great. I'm gonna close down the welcome screen. I am gonna click open folder. And I'm gonna go on, for me, I'm gonna go to my C drive and I'm gonna create a source folder. Now, depending on your operating system or what your preferences are, you may want to create a folder somewhere else. But create a folder because we're gonna put some JavaScript files and later some HTML and CSS files in that folder. And we're gonna want a folder structure. So right here in the open folder dialog, I'm going to right-click and select New Folder. I'm gonna call this Source, Lowercase S in Source, and then select that folder. Now, that becomes the working folder that I'm gonna use to add additional files and all the work that we do for this course inside of there. It doesn't really want me to put Get, Install Get, and I don't want to do that. What I really want to do is go to Terminal, all right, and depending on which operating system you're installed on, you might see something different here. In Windows, you see PowerShell. It doesn't really matter. As long as you get a command prompt. And here I'm gonna type node-v, and I can see that. That's awesome. And then what I want to do is add a file inside of this folder, this working folder. So I'm gonna click on this little file with a plus symbol in the upper left-hand corner. I'm gonna type in app.js. And it opens up a new file here in the main area with a little JS icon right next to it. And here I'm gonna type all lowercase console.log, hi. I'm gonna go to the end and hit a semicolon. So let's kind of walk through this. The word console, a period on your keyboard. The word log, L-O-G. And then an opening and closing parenthesis. Inside of there, I wanna put an opening single quote mark and a closing single quote mark. And then some word. I put hi. You could put your first name. It really doesn't matter. But what does matter to me, at least, is that you end it with a semicolon. And as you're gonna come to learn, writing code is an exercise of precision. If you don't write exactly what I write, there's a chance that you will not get the results that I get. And so you wanna double check and make sure there's not extra spaces. You wanna double check to make sure that you're using the right characters. Like this is not a comma. It is the period on the keyboard. All right. This is not a curly brace. It is a parenthesis. This is not a double quote. Although that would be acceptable. In this particular situation, I would prefer if you use the single quote, which is on the same key, you just have to hold down the shift key to get to it. All right. So now I'm gonna use Ctrl S on my keyboard to save, or it might be Command S if you're on the Mac or something else on Linux. I don't know whatever you use. Or you can just go File, Save. All right. Now, watch what happens when I just use the spacebar on the keyboard. Did you notice, see that little symbol there? It went from X to a circle. That means that file has not been saved yet. That change that I made is not saved. So here again, I'm gonna use the keyboard shortcut to save it. Then I'll come back down here into the terminal. Now, how can I do this easily? Well, on Windows, the keyboard shortcut is Ctrl and then the back tick. That's usually next to the number one, kind of to the left of it on most keyboards. So the back tick will close and open up that little terminal window at the bottom. And now I can type in Node, Space, and then I want to use the name of this file. So app.js. And hit Enter on my keyboard. And it should print out that word, Hi, that I have inside of those two single quote marks in console.log. All right. Now, we can also shorten this up. Node, Space, App. We don't have to use the file extension, and it will work as well. All right. So assuming that you were able to follow along and you got to this step, then you're ready to move forward and we're ready to get started actually writing some JavaScript. Let's start that process in the next video. We'll see you there. Thanks. So our job as software developers is to author code, which is using a language that's human readable and author in such a way that can be understood and parsed and interpreted and ultimately then executed by a computer. And the code that we write, we save into files and we ask some execution environment, whether it be a web browser or in this case, Node, to take a look at this code that we wrote in this file and to interpret it and to execute it. All right. And so it's important, first of all, as we get started, to understand that how our code is going to be used. We're working and learning the JavaScript language, but ultimately the code that we write will be executed in, let's be honest, one of two, maybe even a third environment. We're either going to write JavaScript code that will ultimately be executed in Node and typically when we're writing code for Node based applications, we're writing applications that can access the file system, access the network, respond to HTTP requests and provide an HTTP response, things that are more server side in nature. All right. And then we'll also then write JavaScript code that will execute in the context of a web browser. And we would expect for that code to be able to dynamically interact with elements, HTML elements on a given web page. All right. But we might also use JavaScript to write video games in an environment like Unity, for example, and be able to author and control the various objects on screen and their animation and their interaction and so on. So there's what I'm trying to get at here is that there's a difference between the language itself and then the environment that it runs inside of. And we need to be aware of that, that those are two separate things even though sometimes they feel like one thing. In this case, console, for example, the console.log function is provided to us by Node. It allows us to tell Node that we want to print something to the command line like we did just a moment ago. Now there's also a console.log function in most web browsers and it allows us to print little debugging messages or console messages that can only be viewed inside of a web browser whenever we have the developer tools open. And we'll see how to do that much later in this course once we start building web pages and JavaScript that can interact with them. But at any rate, let's get back to the matter at hand here. If I write my JavaScript incorrectly, then the runtime, whether it's Node or a web browser, won't be able to compile it and it'll give us an error. And so JavaScript is similar to English in so much that JavaScript has a syntax and it has a proper syntax versus a syntax that's incorrect. So if you've ever taken an English class, you'll know that there are parts of speech that you're supposed to use punctuation at the end of a sentence to indicate the end of a complete thought. There are nouns and verbs and adjectives and ad verbs and prepositions and all these sorts of things, right? And so, you know, in general terms, the same thing is true with JavaScript. There are parts of speech. We'll talk about those. And so you will be learning a new language starting with your ABCs and with, I guess, vocabulary words, so to speak. And then to move on to authoring sentences that are complete thoughts and then stringing those sentences together into paragraphs in order to accomplish some higher level tasks and even kind of arranging those paragraphs together to create entire applications, alright? So hopefully that analogy will serve you well as we get started here. Our goal as we get started is to author JavaScript statements and a statement is basically just one complete instruction. It's like a sentence in English and each JavaScript file that we create, like this app.js, it'll contain one or more JavaScript statements that will execute in sequential order from top to bottom, at least usually. And I'll talk about the exception to that as we get further into this course. But there are some other similarities between JavaScript and English. For example, there's an end of line character. I was very specific about adding that semicolon at the end of our statement and that just is an indication to the compiler that this is a complete thought and it should be carried out as is, alright? Now, we also see that we have our statement all on one line of code and generally speaking, as we're getting started, we're going to write our JavaScript statements one per line. Now we'll bend those rules as some of our statements become very long. We can actually, for readability's sake, from a human perspective, we can split things up on the multiple lines if we need to. JavaScript, specifically Node, doesn't really care about that. That's really more for human readability. It can deal with multiple lines or a single line for a given statement, but be that as it may, we're going to try to strive at the beginning to write one statement per line in our files. A statement usually consists of one or more expressions. We'll talk about expressions a little bit later, but this particular expression is essentially just executing a function that's built into Node. It's the log function. It belongs to an object called console. We'll talk about objects and functions a little bit later here and we execute it by using operators, those in this particular case, this is the function vocation operator or the method invocation operator. It's those open and closing parentheses. We can even then pass in what are called arguments to those functions. You can see that each little piece of this has a name and it has a role to play in creating our functions and we'll learn more about that as we move on here. One thing to note is that JavaScript is case sensitive and this trips up a lot of people to begin with. That's why I was very specific to say, hey, don't accidentally or mindlessly use capital letters to make sure everything is lower case. Let's see what happens if I were to save this work that I did here with the capital C in console and the capital L in log. Let's go node space app and hit enter and we get a reference error console is not defined. It's not defined inside of node. Console doesn't exist with a capital C inside of node. It exists with a lower case C inside of node. The same thing is true with the function name log. Let's go ahead and I'll just use the up arrow on my keyboard that'll give me the last command that was used in the terminal. So again, node app and I'm going to try to execute this little program again and I get another error this time console dot capital L log is not a function. That's true. It's because it's lower case L in log and I'll save that change and then we'll re-execute this and it will work. Now there are some things that, especially when your application is small, don't matter. So you might have accidentally left off that semicolon at the end and the application still runs but that's a bad practice to rely on that. You should always try to create properly formed sentences even though you could write an English sentence or a text message that somebody could understand that has no punctuation, has no capital letters and things of that nature that would make it a well-formed English sentence and you're relying on the person receiving that text message to understand what you're trying to say. The computer doesn't work that way. It needs to know exactly what you're saying and so you have to be precise. Precision is the key as a software developer. All right, so what I want to do here as we kind of start wrapping things up for this first foray into JavaScript, I'm going to comment out this line and add some new code below it and use that as kind of the next step beyond where we're at right now. So to tell the compiler to ignore a line of code, I'm going to add a code comment and here I use two forward slashes. I added also a space but that was really just for readability sake so that myself as a human I can kind of make an easy distinction because sometimes all these characters run together. I like adding a space between this but these two characters say everything out on this line of code don't compile it, don't try to use it, all right? And we'll see in a moment that there's another way to create code comments as well. But here let's create something a little bit more interesting. I'm going to say let x equal 7. I'm going to say let y equal 3 but z equal x plus y and then we'll do console.log and then I'm going to use open and close parentheses I'm going to use a single quote I'm going to type in the word answer colon space I'm going to go outside of that quote so I'm going to go between the closing single quote and the closing parentheses and I'm going to make some space for myself in there I'm going to use the plus key or the plus operator and the letter z I'm going to go to the end of the line character, the semicolon I'm going to save it all Now before we actually execute this what do you think this will do? What do you think will be printed to our console window? Do you have any guesses? I'm betting that your background in math or algebra probably will lead you to the correct answer and I think that your intuition in many cases is something that's important as your learning JavaScript it is human readable it should be somewhat understandable it might require a little extra explanation because there's some things that are not extremely obvious but for the most part this shouldn't blow you away and nothing we cover should ever blow you away it just might require a little extra effort than you're normally used to putting into things but by no means impossible, right? So just take some comfort that this is well-traveled ground and that if I can understand it let's run the application and see that we get the the correct result which is answer, colon, space and the number 10 so how do we get that? Well, we have something here, let X and even though, again you're not a JavaScript developer or an advanced JavaScript developer just yet I'm willing to bet that you understood that we were creating a variable essentially that could contain a value and immediately we set that variable equal to the value 7 and then we did the same thing with the value of 3 we put that into a different variable a different bucket called Y and then here we have an expression an expression that will add two values together what are the values inside of those variables X and Y well we just assign them in line string 4 and we know that probably means we're going to add those together to get the result of 10 and we assign that into a new bucket a new variable named Z and then we merely print out that literal string but then we also say also append the letter or the value that's in Z now hopefully that made sense to you even before we ran the application but you can see here that for example the plus symbol has double duty it's serving to be the addition operator but it's also serving to concatenate two values together in this case two string values together so that we can print it out to screen so we're going to use this kind of as a starting point and talk about this at more length in the next in subsequent videos but hopefully up to this point you get some comfort level you're writing some code you're getting your hands dirty in the code and you know I know you can do this so just keep pushing forward and let's pick it up in the next video we'll see there thanks in this video I want to continue talking about line number three so that we completely come to a full understanding of what variables are in JavaScript so I'm going to add a new file and I'm going to do that by hovering over the source tab of the explorer and I want to type in variables.js like so and then I'm just going to copy in the code that we had here we use this as a starting point alright so let's focus in on line number one let's just first of all let's make sure this still runs and let's go node and this time we're going to give it the new file name variables and we get the same result as before great so what is a variable I think I said at the very end of that previous lesson that a variable is basically just a an area in the computer's memory where we're storing a value we're requesting or declaring our need for a new variable a space in the computer's memory where we can put information and retrieve information and then we can from that point on continue to use that variable to store different values and retrieve those values back out throughout the life span of the application so there are actually several different parts to the variable declaration statement in line number one the first is the let keyword and let's start talking about the parts of speech in JavaScript a keyword is something like let and we'll see some other examples later but essentially think of it like a verb in the English language it's an instruction to the JavaScript compiler that we want to do something that we want to take action so we want to create a variable with the name of X and we're expressing that intent to JavaScript using the let keyword so that's the first part of it and then the second part is the name of the variable that we want so we're requesting that an area of storage a unit of storage is assigned to our application where we can put things but how do we reference that again it needs a name so that we can get the values and put new values in memory alright and so that's usually called an identifier we want to declare a new variable with the identifier of X and we're going to talk about naming our identifiers naming our variables there's some rules and some conventions that we need to follow as developers alright we'll come back to that at the very end of this lesson now before we get too far there's actually a couple of different ways to declare a variable in JavaScript the original keyword that you'll see used and used in 99% of all tutorials and articles and books and videos is the var keyword and until recently this was the only way that you could declare a variable in the latest version of JavaScript however the recommendation is to abandon var unless you really need it use the let keyword instead or the const keyword which we'll talk about in just a moment if we were to save our application using the var keyword in line number one and then rerun it nothing would change so what's the problem with var there are some well I guess there's two ways to kind of explain it at this point the first is that its usage is very nuanced it does stuff that somebody new to JavaScript may not anticipate the ramifications of until it's too late and there are problems in code we'll talk about the var keyword and how it relates to scope and so on in an upcoming video but we need to introduce some more concepts before we can get to the point where that discussion is even interesting okay so it's usage is nuanced and the ramifications can be pretty challenging if you're just getting started so that's why the people who decided what goes into JavaScript said why don't we introduce a new keyword called let it will work like most other programming languages as you try to learn JavaScript hopefully it won't be problematic so that's why we have the let keyword the other keyword for declaring a variable is const and we use that whenever we want to express our intent to the JavaScript compiler that we do not intend for that variable to ever change its value so what we initialize the value to in this case to 7 we wouldn't expect that to change throughout the lifetime of the application and if we try to change it like in the very next line of code we can attempt to set it equal to 6 I'll save that let's go over and try to run that code we're going to get an error and it actually is pretty helpful it gives a little carrot right underneath the equal sign and it says assignment to constant variable that's the problem and the issue here is that we've said to JavaScript we never want to change that value and then the very next line of code we say yeah I'm going to assign it a new value and set it equal to 6 and it says can't do that so for the most part we're going to use the let keyword most of the time because that's the recommendation now in as we learn JavaScript alright so just want to point out that we can uncomment out line number 2 as we assign the value of x to different values and we can keep doing this as many times as we want to so at this point in line number 1 we've declared the variable set it to the 7 then we've assigned the value of 6 then 5 then 4 we can keep changing the value in the computer's memory and what is the value in line number 6 what's x's value well the last time we assigned a value to it was 4 so the application now whenever we run it will give us 7 because 3 plus 4 equals 7 right so that's what we get in line number 7 great alright so I guess this should be obvious at this point the equal sign here is actually what's called an assignment operator this is how we assign a value into a variable and we can keep assigning values as many times as we want but we can only declare value our variable one time so if I were to try and come down here and say let x equals you know 7 again or let it equal 8 I'm going to get an error whenever I try to run the application the identifier x has already been declared again you can only declare variable once but you can assign its value as many times as you want to after that alright so in line number 1 not only are we declaring the variable then we're also assigning its value right off the bat in the same line of code and when we do that it's a technique called initialization this is actually two lines of code rolled up into one lines lines number 1 and 2 now are roughly equivalent to what we had before well roughly equivalent there is one difference here at the end of the execution of line number 1 what is the value of x well let's find out console.log and then we'll just say what's the value of x at this point and then let's run the application and you can see that first value that's output above what we get now in line number 11 is the term undefined we'll explain what undefined means in more detail a little bit later but essentially it is what it sounds like we've declared a variable but we've not defined it we've not put a value into it so it's undefined and that's generally not something we want it might be in some cases something we need but for the most part we won't do that at the moment of declaration you also initialize your variables if you can alright so that would be valid right there alright so now let's finish this up and talk about the rules for naming our variables the variable name itself I think I've already referred to this as an identifier and so there are rules for identifier names and then there are some code conventions and these are not enforced by the JavaScript compiler but are rather things that are best practices as determined by the community of software developers who've come before you so let's talk about those things which are hard and fast rules that will actually break your application rule number one is that all identifiers, all variable names have to begin with either a letter a dollar sign or an underscore so that's rule number one the variable names can contain letters or numbers dollar signs or underscores but no other special characters and you can't use a space in between two words that you intend to be considered together as an identifier identifier can't have any spaces and then rule number three is that you can't use any keywords so I can't do something like this let equal to eight and if we try that we're gonna get a weird error let is disallowed as a lexically bound name alright and so even if we were to scroll up just a tiny bit it puts that, those carrots right underneath the let the second one because we're trying to use that identifier but it's already a keyword right so you can't do that alright so those are your own oh yeah there's one other rule and that is that variables variable names identifiers are case sensitive so we could do this and it would be a perfectly acceptable application these are two different variables uppercase x and lowercase x so if you intend to do something like this let's see what we get here alright it doesn't it doesn't blow up so we were able to use x and assign it to eight but we didn't declare the variable well something fishy is going on and we'll get to the bottom of it before the end of this course but the key to this is that we did not we're not working with the same x as we're working with here alright so let's just get rid of that but those are the rules has to begin with a letter a dollar signer underscore the rest of the name can have pretty much anything including numbers but no spaces or other special characters can't use any keywords for names of variables and be aware that variable names are case sensitive now there are code conventions and these again are just good practices the first one is that variable names should be descriptive and unfortunately x y and z are not very descriptive names ideally we would use something like maybe let's go down here so let first number equals seven and then let second number equals three and then we could use that in line number 12 instead here's some better ones actually like if we wanted to capture information or represent information like the first name or let the code two equals zero two and so on alright so use names that represent the thing you're trying to store and it from an application perspective what meaning does this variable have inside of our application meaningful variable names the second is camel casing so if you are going to use multiple words you should use this format called camel casing and that means that the first word of your variable name should be lowercase so the f in first is always lowercase but then any subsequent names that we append or words that we append together should have a capital letter so you can see that I follow this convention every single time in lines 15 through 18 lowercase z in zip code capital c in zip code alright so camel casing third one is to be consistent and that is to always follow the same kind of naming convention and this would be true kind of a cross not just the names of variable names but for every other type of identifier that we wind up creating in our application stay consistent pick one style and stay with it throughout the remainder of the application and then the other is to not rely on case we've already seen the danger of that but what if I intentionally wanted to let zip code equals 60459 what we've just done while it's grammatically correct from javascript perspective and those are two separate variables in line 18 and 20 we've introduced some subtle dissonance in the application now it's more difficult for me to see that these are actually two different variables and maybe I intended to do that but that's poor programming practice we might choose maybe a better name like first zip code and second zip code that might be a better way to go about that same sort of thing okay so those are the code conventions and the naming rules for variables and that's just about everything you need to know about variables just about there's actually a little bit more that we need to talk about and we'll finish up this discussion in the next video when we talk about the values that we're actually assigning into variables and their data types and we'll talk about that next see there, thanks in this video we're going to talk about the values that we store in variables and we're going to talk about the types or rather the data types of those values and why they're important so to begin with let's go ahead and create a new file called data types.js and this is where we're going to do all of our work and one of the things that makes JavaScript so unique when compared to other programming languages is that whenever you declare a variable like we do here let x equals 7 the variable itself does not have a data type only the values that we store inside the variables have the data type so we kind of see this whenever we're working with variables we can use something called the type of operator and this will tell us the data type that we're working with so well let's go ahead and go back to here let x equals 7 so let's start off by just going console.log and then we'll say type of all one word lower case and then x and let's save that save it and here I'm going to type node and then data types and you'll see that it outputs a number so that's one of the first data types the x data type is a number and a data type is really just the kind of data that we want to store so if you want to perform math or some algebraic operation then you want to use a number and if you want to do a yes or no true or false evaluation then you'll want to use a boolean and if you want to display something on screen then you'll want to use a string which is basically a shorthand for string of characters and you usually represent those with single quotes with whatever string of characters you want to use inside of it so let me give you a few examples here we've already looked at number let y equal true and so then we'll do console.log type of y and then I'll just go ahead and do z as well let z equals hello world and then console.log z oops not to z I want type of z alright and so now let's go ahead and run this and we can see that we get the three data types that we're currently working with a number, a boolean, and a string so in the case of a number it can be any positive or negative number it can even have decimal values in the case of a boolean it can either be true or it can be false those are the only two values and then if we want to create a string it's going to be anything inside of the single quotes it's a literal string of characters I literally want H-E-L-L-O space W-O-R-L-D alright and so those are your three of your seven basic basic types data types there's also another case let's let A and then console.log the value of A and then console.log type of A alright and just to remove the confusion here I'm going to use a multi-line comment this allows me to avoid having to do this on every line right I can just do this little slash star at the top then go down to the bottom of where I want to comment out and then star slash you can see everything that's highlighted in green or turn to the green color is now commented out just as if I commented out each individual line separately so here I'm just creating a variable A but I'm not initializing it to a value remember we saw do you remember what an output when we did this before it output the value undefined but we want to see what the type is said that it's the value that's assigned to the variable that has a type so what is the type of a variable that has nothing assigned to it well that's what we're going to get to the bottom of right now so we see that the value is undefined and the type is undefined so now we have four types we have number boolean string and undefined and there's two or three others that we're going to look at here before the and we'll get to them they're a little bit more complex but those are the four that we have to work with at least to start off with and so that's all I really wanted to say the next thing we're going to talk about very quickly is how I would convert one type into another type how do I force javascript to treat a string like this console.log and then a literal string of the value 9 how do I make it treat it like the number 9 well we'll talk about that in the next video we'll see there thanks in the previous video we learned that values not variables have a data type and that the data type is essentially a description of what you want to do with the data there's more to it than that but for our purposes right now it's essentially what we intend to do with the data and we learned of four data types and we'll learn about a couple more a little bit later there's the number data type the string the bool and the undefined so let me ask you this what happens when we need to use them together and they don't quite work the way that we think they should what options do we have then so let's go ahead and create a new file I'm going to call this coercion coer c-i-o-n dot j-s I think that's how you spell it and let's start off with a quick little example here so let a equals seven let be equals the string the literal string so I want to use single quote six single quote all right and then let c equals a plus be and then console dot log answer and then see all right before we execute this application what do you think is going to be output when we run it what will the answer be all right get that in your mind and now let's go node and coercion and looks like we don't get anything at all oh I need to save this okay there we go let's try that again there we go we get the answer seven six wait seven plus six should be 13 right why are we getting 76 something I can see what's happening it's not treating these as to numeric values it's treating them both as string values so it's not adding two numbers together somehow it's coercing that a from a string from an integer into a string and then concatenating together a and b so this operator the plus operator we saw how we can use it for addition but we also it plays double duty and it's the string concatenation operator but more over JavaScript realizes that it can't add a a number in a string those are it's like adding you know an apple in a car together it's not like making an apple in an orange even these it's not like fruit salad it's like two disparately different things what do I do well I will I will take the numeric value and coerce it convince it force it against his will to become a string and then I will concatenate the two together so that's the notion of coercion and most people consider that to be an evil thing or a very dangerous thing and others just say well it's just what happens you know it's just part of the language now what if I really wanted to perform addition on two integers well then I would need to take steps to force the string six to become a number so that I could then add them together and so to do that there's actually a special function that will force that conversion so let me change this just a little bit and we already have the value B so I'll just reuse the value B and I'll set B equal to parse int now I want you to notice something I haven't really talked about visual studio code much but one of the nice things about visual studio code is that it popped up this little box called intelligence and intelligence is just a visual cue as I'm typing to show me things that I might need to reference or things that will help me to find the right command or the right idea in this case I knew it was something parse so I start typing in and I can then use the arrow keys to start looking I'm like oh yeah there's poor parse float that would give me a number with decimal values but this in this case the string that I want to use I know that it will only be a value without without any decimal points so I want to use the parse int now what I can do is just use the space bar or like the opening parenthesis whatever the next logical character is to do what's called code completion so I don't have to type everything else now in this case I know that I'm going to need to use the parenthesis for reasons I'll talk about later so I'm just going to do an open parenthesis well it didn't do it for me well there we let's just go ahead and use the tab key instead alright so the tab key will give me what I want now I'm inside the the parenthesis and I need to pass in first of all the string that I want to change so in this case take the value of B and then I need to give it optionally what's called a radix or radix and that is essentially the base system so if I wanted to to use like a hexadecimal I might give it 6 but in this case I'm going to give it 10 because I want to use a base 10 or a decimal conversion alright so it's a little technical but typically if we use 10 in there we're going to be just fine so essentially what I want to do is take the 6 and based on the normal decimal system I want to convert that into a numeric value and then I want to continue on in lines 4 and 5 like we had before let's see what we get this time the answer is 13 just as we had hoped alright so the parse int is a built-in function to javascript and I can count on it being available in node or in a web browser or any other implementation of javascript alright so I guess this begs the question what if I try to do something kind of evil with this so let d equal parse int and then use the tab key to do the code completion and this time I'm going to pass in a character that will not convert to a or even a string that will not convert into a numeric value especially when that's decimal so I'm going to save this now let's go ahead and console.log it and d so let's go that and then we'll do this alright and I get n a n which represents not a number it's not really an error it's just telling us that the value we passed in is not a number we could actually do something along these lines as well let e equals is n a n and then I can give it some numeric value in this case I'll give it d and I'll do console.log e so let's save that run it again and so this time now I'm evaluating whether d is not a number and that is true it is not a number because I can see it here I can just print it out alright so we saw two built in functions but there's a bunch of built in functions for various things all kind of centered around in this case just working with coercion and checking the results of that attempt to to coerce or convert one data type into another alright unfortunately there's no parsed boolean so you can't take a string of true or false and convert into a boolean you'll have to take a few extra steps of examples online for that and so depending on the type of conversion that you're attempting to perform it may not be easy to convert from one to the other there's always a way and usually you can find some code online especially on a site like Stack Overflow that will help you figure that out but that's all I wanted to say let's continue on in the next video we'll see you there thanks in this video I want to refocus on the JavaScript syntax specifically and the various parts of speech inside of a properly formed statement in JavaScript so I started by explaining JavaScript by saying that you write statements each of which are executed sequentially and statements are complete thoughts complete instructions to the JavaScript compiler of what we want it to do for us and I said the statements are made up of one or more expressions of the type of operators and operands and I just made that statement in passing and kind of blew past it really quickly but I wanted to take a few moments and explain why that is an important statement whenever we're setting out to write code and so we've already looked at a couple of different operators if we're thinking about the most atomic level of our JavaScript statements we're thinking about in terms of operators and operands so operators are key words we've already looked at the addition operator using the plus symbol we looked at the string concatenation operator using the plus symbol so that one is doing double duty and it will be understood based on the context of how it's being used and then there's the assignment operator the equal sign that we've already looked at and soon we're going to look at a few other common ones just to start building out a list of operators that we can use to do more interesting things inside of our application but there's also an operand so operators are things like keywords and those various symbols that we've already looked at and we'll add more operands are something like identifiers a variable name we'll learn about functions soon and functions are another type of operand and so unlike keywords and operators in JavaScript which are fixed in part of the language we and I programmers give operands their name and so by combining operators and operands we create expressions that are then used to compose statements and so sometimes it's easy to spot an expression and then sometimes it's not so easy but identifying several major categories of expressions we can better understand why JavaScript works sometimes and why it doesn't work sometimes so for example in the English language we cannot write a sentence a proper sentence like this the dog period if we've said hey the dog our friend would say what are you talking about the dog did what which dog you know give me some more information right why is that not a proper sentence in English because it didn't have enough inside of it to be considered proper we have a noun we have the dog but we don't have any verbs or adjectives or adverbs describing or or kind of giving us more detail about the dog the same thing is true with JavaScript so we can't for example and let me just create a quick file here we'll call this expressions.js so we cannot do something like this in our program right because the JavaScript compiler will say ok what do you want me to do with that that makes no sense to me whatsoever I don't know what you want me to do with A I don't see it it's not one of my variables you're not asking me to create a new variable there's nothing inside of A A means nothing to me alright so at a minimum we're going to need to either and these are the types of expressions in a very high level we're going to either declare a variable so we would do something like this once again let A alright and even in this little tiny two word line of code there's already an operator and an operand here's the operator the let keyword and here's the operand a name we want to give to a new variable that will be created in memory alright so that's one type of expression we're going to call this types of expression here we'll just use some comments types of expressions number one variable declaration I spelled that right alright so let's go ahead and just move that up to the very top and say this is bad and then we'll do something like this I kind of like doing some nasty art there whenever I create lists inside of my code alright so there we go the other one is to assign a value so the other type of expression we can assign a value so A equals three or four and then another type of expression is to perform an evaluation that returns a single value so that might be something like and if we're talking purely about the expression itself it might be something like that B plus C so in a more interesting example we might do something along these lines and I'll just comment this out because I want to reuse A there we go good alright so here we go line number 16 I'm going to go let A B equals three let C equal two and then let A equal B plus C I just want to focus on line number 19 and I want to say that there are three expressions in here can you find them alright well let's find them so number one we're going to see that let A so that's a variable declaration the next thing that's going to happen is we're going to perform an evaluation of B plus C right and that will basically add those two values together because we're using the addition operator and then finally we'll do the result of B plus C is assigned to A so three expressions all combined into a single statement and there's a lot more going on than meets the eye but that is the kind of thinking that will help you understand why your javascript code works sometimes and sometimes it doesn't you have to think in terms of writing expressions that do things to form properly formed javascript statements so hopefully that little lesson in syntax is helpful let's talk about operators and the different types of operators and again we've used this collection of five or six operators so far let's let's add to that collection I'm going to go create a new file called operators .js and so there's several categories of operators and I'll just kind of go through them really quickly here so there's assignment like the equal sign it's really the only one in this category but it's a pretty important one we've seen to use quite a bit there's maybe some other keywords and things that can fall into this category sort of but the assignment operator is usually the only one in this category and then there's arithmetic with which as you might suppose would allow you to do mathematical style operations so that's the plus where we're adding two numbers together subtraction multiplication that's the asterisk key over the eight on most keyboards there's also the division alright and then there are some special ones like let's call these and I'll they're kind of arithmetic but I'm going to call them increment decrement so this is the plus plus and the minus minus and use out of context these don't seem so interesting but what we could do is for example let's go var a equals one a plus plus and then console dot log a let's save that and then go over to our terminal and I'm going to do node operators alright and so you can see that we increment the value of a so let's do this let's now increment it one more time and see and let's save our work here and then let's run it again and wait a second the value is still two how is that possible let's do this console log a like that so now we're going to print the value out twice we're going to print it out I thought maybe we would get three but we didn't but if we printed out a second time let's see what value we get and so when we print it out the second time we get three and the reason is this because this operator this increment operator works after the line or after the value is already utilized inside of this line of code so basically hey console.log here's a and after you print that screen then let's add something to it that's why we're able to see the new value if I print it a second time alright what we may have preferred instead of this is to go console log and put the plus plus before the a that means I want you to first evaluate the increment of a and then print it to the console.log alright so let's say that let's rerun this and now we see three in both cases the same would be true with the decrement where we could subtract either before or after the evaluation of that variable alright just something to keep in mind alright so that's increment and decrement there's also going back to arithmetic there's the modulus and this will give me the remainder amount so let's go var m for modulus equals 10 divided by whoops whoops whoops that's not what I wanted 10 modulus 3 and then I want to console.log m and just to kind of keep everything clean I'm going to comment out all of this as well keep it around for posterity but otherwise that's all I want to see what will I get back from this the statement and I get one what is one it's the remainder so 10 divided by 3 equals 3 with one left over that one is the modulus alright and actually this becomes a lot more interesting and important when we're looping through lots of values and every like 10th or 20th or 100th item I want to print a little message to screen to say hey we finished processing the 10th the 20th the 30th the 40th the 50th item alright and I use that actually frequently so I'm a pretty big fan of modulus comment that out so moving on to the different categories of operators let's talk about the various string operators and we've already seen these so this is going to be like the literal string operator we're using single quotes and then also we saw the string concatenation operator that will take two strings and allow them to be appended together to create one new string other operators precedence so we might you know order of operations we actually use this quite a bit even in non-mathematical situations so for example let's just do var b equals 1 plus 2 times 3 now if you're coming from an algebra background there's an order of operations where things should be done in a certain order and I'm pretty sure if memory serves me correctly it's been a long time since I've had an algebra course but you perform algebra before you perform addition so if I were to do a console log here I would expect b to output 2 times 3 plus 1 so that would be 7 let's see if my memory serves me correctly here and yes it does but what if that's not what I want well I can use just like in algebra I can use parentheses to kind of control the order in which things are evaluated so in this case I would do 1 plus 2 first and then multiply that by 3 which will give me a completely different result of 9 because 3 times 3 equals 9 okay so we'll use this the opening and closing parentheses for different purposes for example whenever we want to do console.log these parentheses are also used as the function invocation operators and that just says here's a function name called log and we'll learn about functions soon but I want to actually invoke the function now and I can even use the function invocation operators the opening and closing parentheses to pass in arguments and we'll talk about that a little bit later but again that is the opening and closing parentheses there are other operators and I'll just put them here they may not make a lot of sense at the moment when we look at decision statements so there's the logical if I'm sorry the logical and and the logical or so when I want to add two things together and evaluate two things together either one of them needs to be true or both of them needs to be true and we'll look at that in a little while there's also the member accessor operator so when we did console dot log if you look at IntelliSense as I hit the dot on the keyboard there's that period why are we using a period there that allows me to access the various members of this object and we'll talk about object and we'll talk about properties and functions or methods of objects soon but that's what allows me to access the log function of the console object inside of JavaScript so here again comment that out but we'll use the period for that purpose we're going to also look at the code block operator soon and so you know I'm going through all these and I'm saying hey we'll look at these soon really the point of this exercise is to say that there's lots of operators and we're going to have to begin to identify what all these special characters are and the only way to do that is to first of all learn that they exist what their function is and then use them as we're writing programs and so I think that's really the only thing I wanted to say I mean let me just put one more in here the array element access operator goes by different names but I'm just going to use that and so we'll use square brackets for that purpose so almost every single character the special characters that are above our numeric values and we can access using the shift key and the various ones that are usually on the right hand side of the keyboard the various braces and brackets and colons and semicolons and all of these are are used to for various purposes in JavaScript and in most programming languages so I think that's all I really want to say let's pick back up in the next video you're doing great hanging there with me we're getting through some of the easy stuff and we're going to start moving on to some challenging stuff here really quick but you're doing great see in the next video thanks up till now each variable that we create can store one value at a time per variable but what if we need to work with lists of data in other words I need to keep track of several people or several numbers and I need to store them in such a way that it doesn't matter if I have 2 or 10 or 100 I can kind of keep them together and move them all around and use them in my application as a list as a grouping of related values in that case I want to create an array and so let's start by creating a file called arrays.js and first of all basically an array is basically a variable that can hold many different values and so we can declare variable and initialize its value like so so here we'll do let a equals and here we're going to use an opening and closing square brace or bracket and then I'm going to give it a series of values each value will be separated by a comma 48 let's say 15 16 23 and 42 and so now I have an array of those values. Now these are just numeric values what if I wanted to create an array of string values I'm going to use something similar in fact I can use any data type inside of here that's allowable in JavaScript and we'll see some examples of that a little bit later but I might want David Eddie Alex and Michael alright and then what if I want to get one of the values I can just do console.log inside of here I'm going to use the variable name so in this case I'll use a and then I want to provide a index to retrieve one of the elements so each of these is an element of the array and I want to use an index a numeric value that allows me to get at one of those elements inside of the array the indexes are zero base that trips up beginners sometimes you for example to get at the number 4 the first element in the array I would use the index zero if I want the second item in the array the second element of the array I would need to use the index one and so on I'm going to add it I'm going to use a and then right next to the a square brackets and I'm going to give it an index so here we'll grab the first value and then I'll grab the second value and then I want to do show you how console.log will just print out all of the values for you nicely if you just want to give it the name of the of the array itself so let's save our work and we'll go node arrays alright so you can see the first element of the array at index zero gives us the value four the second element of the array at index one gives us the value eight alright hope you can see the correlation there or if I just want to print out all the values in the array I can just provide the variable name that contains the array it will print them out for me just like I have kind of here when I actually initialized our array variable alright let's comment this out now that is how we access individual elements what if I wanted to change or set the value of one of the elements the same would work so in this case I would say for example a zero and I would set it equal to seven like so and so then we can just do console.log like so and then we run our application now you see the first element of the array has been changed from four to seven because that's how we can access a single element and assign it a new value alright alright so what about these mysterious these mysterious arrays what is their data type so let's do console.log type of A and we can see that it's of type object and we'll talk about the object data type later because there's a lot more to it than just being able to create arrays but it's a little bit more advanced at this point we'll get into it soon just keep in mind that an array isn't a data type of itself it is a type of something called object and we'll talk about objects later alright so the other thing that's important to remember is that an array can include elements of different data types so let me just do let's see equals we'll start with four and then we'll do Alex and then we'll do true alright so we've used three different data types right there and we can just do node arrays oh I need to actually do a console.log see there we go there we go alright so you can see that a single array can hold different data types there's no restriction there let's comment that out what happens if I try to access an element that with an index that does not exist so let's do console.log and I happen to know that the B has four different elements in it four names and let me try to access the fifth element by using the index four and this will be undefined so just like a variable without any value assigned to it is undefined so is a element of an array undefined if we don't give it a value now I can also just programmatically determine the number of elements in an array by using a special property called length so I can do console.loga. and remember the dot is the member access operator so arrays are objects and this particular object has a special property called length which will give me the number of elements in that array so I would expect to see let's see 1, 2, 3, 4, 5, 6 so the question is is it going to give us 6 the actual number or is it going to give us to it in a zero based fashion and the answer to that is that it will give us the actual number not zero based and this will come into play a little bit later when we use the length of an array and we iterate through each element of the array to print them to screen when we learn about looping so just keep that in the back of your mind now there's a lot of strange things that you can do with arrays some of them are not always intuitive like for example if I wanted to just randomly create a new element so in this case I'm going to create what the use the index 10 which means this would add an 11th element to the array what happens with all of the elements between where we left off 0, 1, 2, 3, 4, 5 so 6 through 11 what will we get so let's just assign this to 77 and then I want to do a console.log of a and I want to do a console.log and a.length like we just learned about and kind of see what happens here and let's run that so we can see that it prints out 4, 5, 6, 7, or I'm sorry 4, 8, 15, 16, 23, 42 and then it says there's 4 empty items and then there's 77 and it says that there's 11 there's 11 items, 11 elements in this array because we filled up the 10th index or index 10 with a value so it will create essentially what's called a sparse array and that means that there are empty elements inside now this isn't usually the way that you want to work with arrays if you need to add new values because it's not as safe we're inadvertently creating elements with nothing in them there's a safer way to go about this using some additional built-in functions of the array and so if I wanted to add that value and add it to the end of the array no matter how many elements are currently in the array I could use the push method and so I say hey I want to push the number 77 to the end of the existing array so let's copy this and paste it here and then if I wanted to remove it I can use a method called pop so this function pop will remove the last element of the array in fact I can call it several times to keep removing elements of the array and here we'll just print out what the end result is just like we did previously so now this should put some fireworks into our terminal window so you can see that using push in line number 29 I was able to add the number 77 to the end of the existing array and that gives me 7 total elements now I call pop 3 times it removes 77, 42 and 23 leaving us with just 4 elements in our array so we're going to continue to use arrays they're a great way to keep lists of things together and accessible and they'll become even more important again as we learn how to loop through arrays and to evaluate each element we can even use arrays to hold on to other things like objects and functions and we'll learn about some advanced use cases with arrays a little bit later that's all I have to say about arrays let's move on and start looking into some things that are beyond the absolute basics we'll start moving and talking about functions see there, thanks throughout this course even from the very first line of code that we wrote we use the console.log function to print things to our terminal window and I kept referring to log as a function as part of the console object in its simplest form a function is merely a block of code that we as programmers can name and once it has a name then we can call it by its name but it's just one or more lines of code that we put into a block and then we say we want to execute that block over and over and over again throughout our application so again that's a very basic explanation of what a function is but in JavaScript functions can do so much more in fact most of this course will be devoted to working with functions because frankly they're one of the primary constructs in JavaScript for getting things done so first of all let's go ahead and create a new file I'm going to call this function declarations.js alright and first of all if I have some code that I want to reuse throughout my application I want to add it to a function so we can create a function and I'll walk through and explain the parts of a function here in just a moment let's create the most basic function that I can possibly think of and I'm actually going to copy and paste some code in so we don't have to type at all but nothing here should be all that revolutionary so I've created a new function called say hello notice my name I use camel casing right in order to name my identifier my function name alright and then I have three lines of code notice that they're inside of these curly braces notice that they're indented so we see kind of a relationship between this code on the inside and this line of code and this line of code on the outside so kind of represents a container relationship this code sits inside of or as part of or is rather the body of the function that we just declared alright so here we just declared a simple function this is called a function declaration this style we're going to look at other ways to define functions later and I'll draw your attention and why you'd want to choose one or the other later there's at least two other ways that I'm thinking of off the top of my head but first of all notice that we use a keyword called function then we give the function some identifier that we come up with something meaningful we'll use similar rules to what we use for variable names alright then we use an open and close parentheses you'll see how these will be used a little bit to define arguments or input parameters to our function but right now it's empty we don't require that the caller give us any additional information and then we use the open curly brace here and the close curly brace here to define the container to define the code that we want to be the body of this function and everything inside of that is just any javascript that we want to write for the most part alright so how do we actually then use this well we gave this block of code as defined by the open close curly brace we gave it a name and so we should be able to call it by its name so I should be able to do something like this right say hello and that will get me most of the way there but to actually invoke a function we have to use the function invocation operator in this case it's the opening close parentheses and obviously we want to use our end of line statement here so let's go node and then function declaration and let's see oh declaration sorry there we go alright and we get hello so hopefully you weren't expecting something super interesting we're just printing out three lines with what I would call a flower box kind of around it some dashes to style it up a little bit we can do some interesting things with regards to assigning the function to a variable so let's do let a equals say hello now do I want to invoke the function here no and I'll explain why in a little bit I merely want to get a reference to the function and then I'll do and invoke the variable so this variable is now pointing to this function and now I say okay I have a function inside of this variable go invoke it using the function invocation operators in fact here let's do it a bunch of times just to make sure that we're seeing what we think we should see here and so we can see hello hello hello all three times in a row great so let's comment that out now up to now this function is not all that interesting let me just copy it and I'm going to comment it out and I'll create a new version of this function down here beginning in line 17 and I wanted to actually pass allow me to pass in a name so I can say hello Bob hello Steve right so we'll just create a new argument into our function say hello by giving it a variable name so essentially now we're able to use this variable name in the body and we expect the caller to give us the name it wants us to say hello to so here I'm just going to use some string operators here with name and make sure things are spaced nicely and so here I can do say hello to Bob say hello to Beth say hello to Mr. Tibbles my cat alright and let's go ahead and run it and you can see now how I'm able to reuse that code but change it up by passing in the name that I wanted to say hello to alright so let's comment all this out and let's talk about one more thing that we can do with functions and that is return values from functions so this first function that we created it's merely just outputting we're not expecting it to to perform some operation and then give us some value back but what if I wanted to create a more interesting function that implements some business rule in my system in my e-commerce system like to calculate the sales tax on a given amount say a subtotal of all the items that are in my shopping cart I might create a simple function called calculate tax like so and we'll get to the body in just a moment but I want to allow the caller to pass in the amount that we're going to charge tax to alright then I'm going to say let result just the name of a variable result the amount that value passed in times 0.0825 which is the sales tax where I live and then I want to use the keyword return and then the value I want to return so you can return one value from a function in this case I want to return the amount of tax so I'm going to return result now what I'll do is I'm going to call calculate tax passing in an amount so let's say $100 and I want to capture that into a variable I know it's going to return a value to me so let's just do let and I can reuse the variable word result but I might use something more descriptive like let tax equal calculate tax and then console.log the amount of tax like so let's save that and then let's run it and you can see that for $100 purchase it would charge $8.25 in tax ok but that's what the purpose of the return keyword is to actually give me back something so this is an expression a function invocation expression it's going to give me a value back that I can then assign to the new variable tax and then I can work with that value in this case a number representing the amount of tax alright and I think that's all that I'm going to say about this for now but there's lots to say about functions it's going to again consume the majority of this course and you're going to have to become very familiar with the ins and outs of working with functions and we'll start that process in the next video we'll see there thanks. In the previous video we learned how to create a function declaration and a function declaration and a variable declaration are similar in so much that they both have an identifier or a name because we plan to call them later on in our javascript but what if we don't need a name what if we're in a situation where there's just a need for a function but that function will never be called for the rest of the application we know that then we can take a different tact we don't need to add a new identifier we can just create what's called a function expression and we don't have to supply a name we just give it the body of the function and say here go do this when you need to run some code alright and a good good use of that is whenever we need to create some code that should be in the future so here let me start off by creating function expressions.js a new file and here I want to use the setTimeout method that's available inside a javascript and if we use IntelliSense we can see that there's actually two input parameters to this function setTimeout we're going to first of all need to give it something called a handler which I happen to know is just a function. Now I could give it a function declaration but usually people just create function expressions here for the handler and then the second thing we'll need to do and I'll use the down arrow to move from the first argument to the second argument is to give it a Timeout and so that's the number of milliseconds that I want it to wait before executing this code and I'll show you how that might be interesting in just a few moments here. But the first thing we need to do is create a function expression to pass in so just here right inline I'm going to create a function open, close, parentheses open, close curly braces which denote the body of this expression I'm creating inside of here I'm going to do something simple like console.log I waited two seconds and then here at the very end of the function declaration I'm going to give it that second argument the number of milliseconds that I want to wait before executing that function that function expression so I'm going to say wait two seconds and then I want you to call this inline function I'm creating and the body of it will merely just log out I waited two seconds. Alright so here we go let's go and do node and then function expressions one one thousand, two one thousand and you can see it prints to screen I waited two seconds alright now it's kind of hard to read it like this all inline one of the things in JavaScript that's a little bit challenging especially if you're getting started is the number of curly braces that you'll encounter and differentiating for example this outer set of parentheses and this inner set of parentheses and Visual Studio Code tries to help you like when I put my carrot right next to that opening curly brace it tries to find the matching closing curly brace and you'll see as we add more curly braces for different purposes and indentation levels inside of our application. Visual Studio Code does a pretty good job most of the time of finding its match it's just a matter of looking for that carrot that surrounds the closing one here over you can see whatever in column number 61 here I'm looking at the bottom okay anything inside is just the body of the function and the same rules apply whoops I didn't use a semicolon at the end of that line but I should have it shouldn't change the function in this simple case but nothing changes about how we work with this now to be honest most people do not put this much code on a single line I may want to split this up into multiple lines so I would do this in a way that feels natural to me and you can see that as I put my mouse cursor next to where I feel like the split should have been like in the beginning of console.log and here at the end of our body of our function expression Visual Studio Code naturally will create some indentation now if I don't like that level of indentation I'm free to come in here and to change it up like I would prefer to use a tab here so I'm using the tab key on my keyboard to move things out and the shift tab to move things back that only works if my mouse cursor is here right at the beginning of that line if I were to move one character in and use the tab key well that's not what I want at all that's going to split that word up but if I use the keyboard the arrows on the keyboard to maneuver and then the shift tab to move it out I can move things in and out but that is pretty much how I would like to see that function represented right and then I use a comma to pass in a second argument in this case the number of milliseconds to my set timeout function alright so but the focus of this is that function expression I never want to use that function again but I need it in this case as an argument to pass into my set timeout function so functions can take functions as input parameters okay so just keep that in mind because things are going to get a lot crazier than that and let's move on and talk about using both the function declaration and a function expression to do something just a little bit more interesting here same basic idea here but what I want to do start off with a counter and this will count the number of times that we actually execute our function expression I'm going to start with a function on the outside function timeout let's call this function timeout like so and then inside I'm going to set timeout using that built-in function to JavaScript and pass in a new function expression alright and then I'm going to here give set timeout say in two seconds I want you to basically run this function expression that I've defined right there so I pass in the second argument of 2000 again using visual studio code to help me find the matching set of parentheses at the beginning and the end to pass in the input parameter to the set timeout function recognizing that the function expression is the first argument to that and 2000 is the second input parameter to that set timeout function here's what I'm going to do now append so I'm going to put a little space there between high and the closing single quote mark counter but I want to after every time I reference counter I want to increment it by one so this will allow me to count the number of times that set timeout has run now one of the things that I want to do is after I have printed that line I'm going to schedule the next time this code should run so I'm going to schedule and call timeout in a recursive manner so I'm using the name of this outermost function and saying hey now that you've run me run me again in two seconds because I'm going to basically call set timeout again now I need to kick this off the first time so we'll call set timeout once here on line number 15 and that will kick things off and then I'm going to hit control and C on my keyboard to stop the execution because it will just keep looping and looping and looping. Alright hopefully in your mind you understand the sequence of events here I'm going to call this function declaration once the body of that function will create a set timeout in two seconds I want to execute this function expression which will not only show me the number of times that this function has been called because I'm keeping count of it in that counter variable but then also it's going to call the timeout function again which will schedule two seconds from now the next call to the set timeout function ok so let's see it run hopefully this all makes sense so I waited two seconds saw it run once alright so twice three times and see it will just keep going every two seconds until I hit control C on my keyboard to stop its execution alright the last thing that I want to show you now comment all this out is that you can create a function declaration or I'm sorry a function expression that says something like console dot log and I'll make something a little bit more interesting later and then I can immediately invoke that function by first of all surrounding this function expression in parentheses just to kind of say hey I want to group all this together and then using another set of parentheses as the function invocation operator like that do you see that format so there's this inner set that we use to define input parameters we don't need any but we still needed in order to create a function expression then we're going to group this whole thing together and say I want to execute it so there's actually four sets of parentheses we just have to keep them straight in our mind what each of them are doing but this last set will do what's called and this kind of structure is called an immediately invoked function expression in other words I will have function expression and I want it to be invoked I invoked immediately when this application is run and this actually is a pretty common pattern in JavaScript development it comes in super handy and we'll talk about why it comes in handy a little bit later but we want to just remember immediately invoked function expression it's also just known as an I I F E sometimes I think it's pronounced iffy all right so keep in mind if ease and we'll come back to them a little bit later all right so let's move on and move away from functions just for a little bit we'll come back to them later but hopefully you can now tell the difference between a function declaration of function expression most importantly for our purposes you want to keep in mind what immediately invoked function expressions are okay all right so we'll come back to this and let's move on see the next video thanks in this video we're going to talk about decision statements there's actually three that we're going to consider the if the switch and a ternary operator and so whenever we need to add logic to our application in other words perform different blocks of code based on some condition that we evaluate will want to use one of these decision statements and so let's go ahead and start by creating a new file called decisions.js and here what we'll do is start with if statement so the basic structure looks like this if and then we'll evaluate something here some expression so let me just kind of start off with this some expression that expression should equal true or false and there's lots of ways to evaluate this we'll come back to it in just a moment we'll consider those in between the opening and closing parentheses if that is true whatever that expression is then we'll execute all the code inside so let's begin simple bar count equals three hard code of value and then say so if count and then we'll use the equality operator so this is going to evaluate for equality if count indeed is equal to four then we will that expression will return true if it's true then we'll perform whatever code we write here so console.log and count is four so the first time we run this we're not going to get really anything alright so the first time we run this we're going to not get anything it'll just exit what we can do is change this to count equals three like so and now when we run it we'll see the message count is three very uninspiring let's set this back to four and here we can consider the alternative that the count is not equal to four and we could kind of give the counter message count is not four this much we know to be true alright alright so count is not four we basically skipped over this block of code because this returned false therefore we executed the else statement this second block of code and skipped over the first one so there's actually several different variations of this we can use because there are some different conditions here maybe I don't want to jump right to that else statement maybe I want to keep evaluating I can use an else if and so here I might say else if the count is greater than four then I could maybe do a message like console dot log count is greater than four and I can do kind of the opposite as well else if count is less than four so console dot log count is less than four because that changed modalities there and then at that point this will never happen ever because one of these three conditions would occur we'd never get to this final else statement right it would just never happen so let's save our work here and see this run count is less than four because it's three okay so that's the general structure of the if statement it allows us to evaluate one or more expressions if it returns if that expression returns a true then we execute the code in the code block associated with that expression we can create optional else or else if statements to continue to evaluate other expressions usually you want to make related ones but you don't necessarily have to although that may not make a whole lot of sense depending on your business rules and then we can finally use a catch all in case none of the previous else if statements are correct and kind of capture that so let's go ahead and comment that out that's our first structure we'll use the if statement a lot the next type of statement is a switch it's a little bit more tricky to use let's start off with just typing out the switch keyword and what we want to evaluate and so what we'll do is actually evaluate whatever's in this expression against a number of cases so I might for example let hero equal Superman and then depending on the hero I might want to print out the superpowers that that particular hero has so based on the hero if that hero so if the case is Superman I would say well that hero has console.log super strength may also have x-ray vision all right let's add another case here and say case Batman and notice that kind of the format of this to use the case keyword inside of this block that belongs to the switch the case keyword the value we want to compare our case against and then a semi colon and everything that will become part of the body of that case that gets executed so in this case we'll say what are Batman superpowers he has intelligence and he has fighting skills all right and then we can also then say well the default for that hero is that they're a member of the JLA now watch how this works it works a little bit different than the if and else if so let's go ahead and say what we have and then rerun this all right so in this case it was Superman and notice that we matched the case Superman because it prints out super strength and x-ray vision but then everything else inside of all additional cases including the default case will be true as well so he also is intelligent he has fighting skills and he's a member of the JLA now if we were to change this to let's say Batman and we were to run the application you'll notice that it skips over all of the console log statements that describe Superman superpowers and they come in however here at Batman so console log intelligence fighting skills and he's also a member of JLA now we could try somebody like Green Arrow and not particularly one of my favorite heroes and he's just a member of the JLA all right now if we don't want that that flow through style what we can do is actually use a break statement in here so let's go back through this now and see what happens whenever we break out of a given case so back to Superman and now when we run it we only see that he has super strength and X-ray vision Batman has intelligent fighting skills and then Green Arrow is just a member of the JLA okay all right one other quick tip here is that whenever you're evaluating strings there's a possibility like for example Batman what if we had capital B in Batman and then we run the application and you see he's a member of the JLA why didn't it catch the case Batman because capital B Batman is not the same as lowercase B Batman in that string now what we can do to circumvent that whenever we're working with strings and we want to do some comparison with them we can use the two lowercase method of our strings so strings have a built in method called two lowercase and that will take whatever that input is and it will make sure that all the letters are lowercase so that we're really comparing apples to apples instead of apples to oranges so now when we rerun the application we get what we would expect with Batman okay all right so let me comment this out we've looked at the if statement we've looked at the switch and then the third one we're going to look at is the turn area operator and this is useful whenever I want to I want to just do a quick inline evaluation of some expression and then return back a value a string number boolean whatever probably it's a string or a number back depending on whether that expression evaluates a true or false very small short concise inline statement so I'm going to create two variables I'm going to do something a little bit different though the first variable like you would normally expect but instead of ending that line and moving to the next one I'm going to do another variable creation variable declaration and assignment right here in the same line so I'm going to create another variable called be and initialize its value to the string one right so just slightly different technique you might see that online moving on so we're going to create another variable called result and we'll set that equal to some evaluation of an expression does a equal be so two equal signs that are next to each other is the quality operator this is a check for equality to say does a equal be and if that is true then what we'll do is return the word equal as a string but if it's not true then notice the colon that separates the true from the false will return the word in equal so the ternary operator has kind of got several parts here there's an expression there's a question mark that that has true or false ramifications and we'll just do a console.log result so so now let's go ahead and run that and these are equal great we could also do this in line so let me just take this part right here and do that instead you can see how we can basically perform that same check without having to create a new variable to hold the result alright so it's a nice inline way of running a quick check and then returning back a string one string or another string now let me just go back for a second here or actually let's do this and then we'll do console.log result let me comment this one out I want to keep it around for you in case you want to reference that in the future we used two equal signs but there's another type of equality that we can check for and that strict equality and this will check to make sure that these two values are equal but then in addition to that it will not coerce for example the number one and the string one it'll say are these absolutely equal even with the same data types alright and so in this particular case we should expect a different result these are in equal they are not the same alright so these are the same because I'm looking for equality but if I'm looking at strict equality and I'm not allowing javascript to coerce the integer into a string and then check for equality then I have to say no these are not the same because one is a number and one is a string alright so let me comment that out and let's take do one more check here in this case I'm going to use a different operator the not equal to operator so I'll use the word not unequal and not not equal and not unequal alright which would be the same as saying equal alright so now let's see and run that and this produces a false so this would be returned back and then displayed on screen but then we can also do strict inequality by adding another equal sign to that operator and these are not equal again because it is true that A is not strictly equal to B because they are different data types alright hopefully that makes sense alright so let's go ahead and stop there and hopefully and you're doing great we'll see in the next video thanks in this video we'll talk about iteration statements iterations allow us to loop through a body of code a block of code a number of times until a certain condition is met and there's a couple of different types of iteration statements we'll look at two in this lesson and we'll even look at them in relationship to a raise something I promised several lessons ago so let's start off by creating a new file and call it iterations.js and inside of here we'll create our first for loop so for and then there are three parts inside of the opening and closing parentheses first of all we'll let i equals zero or we can actually just shorthand this and not even use the keyword let and here i less than 10 i plus plus and so this is going to take some explanation let's just get this working first and then I'll come back and I'll talk about it and we'll just print out the value of i alright what do you think is going to happen here if I didn't tell you anything about how the for loop actually works what do you think will be printed the screen when we execute our script let's find out so let's go here and type in node iterations alright so we get several looks like 10 different values printed to screen each on a separate line 0 through 9 and then our application exits alright so let's talk about this it's a shorthand syntax and there's three parts as separated by these two semicolons inside of this this evaluation header for the for first of all we declare variable in this case I've declared i that's why we use the let but then I said we don't really need it let's keep it short so we're declaring it and then we're going to initialize its value to 0 the second step we're going to say continue running this for loop as long as this condition is true so as long as i is less than 10 continue running the body of this for loop as defined with this set of curly braces here and then finally after you run an iteration increment the value of i by 1 and here we're going to then print out the value and that's why we start at the value of 0 and then we work our way all the way through this 10 times on the 10th time i gets incremented to then this check is performed it's false and then we exit out the program now let's do something a little bit more interesting like I suggested before let me kind this out here let's go let a equal to and this should look familiar for 8, 15, 16, 23 and 42 whoops I guess I forgot equal sign there and now what we'll do is for i equals 0 i is less than a dot length i plus plus inside the body of this we'll do console.log a and what element we'll use i because i will start off with the value of 0 and it will continue until we get to the length property which is not 0 based and once we get to for example the 0, 1, 2, 3, 4, 5 so length will be 6 elements so once i is 6 it's no longer true that i is less than the length of this array and we'll exit out so let's go ahead and save this and then run and we can see we get all of our values printed out to screen so that's the proper way to iterate through an array. Now one thing about Visual Studio Code that I really love is that they have this notion of code snippets so if you ever forget this syntax and it can be a little daunting at first there's a way to remember it perfectly every time and that is to let the code snippets build it for you so I type in the 4 key word until a sense pops up a little window under it and I'll use the arrow keys to go to the 4 loop there's a couple of 4s but the one that we want has this little box with dots underneath of it that tells me that this is a code snippet I hit enter on my keyboard and now I get the basic structure of my of my 4 loop already created for the purpose of an array. Now notice that every word index is highlighted and I can change that every instance of that by just using a letter like I'm going to change this to the letter B instead of index and notice that it changed it everywhere and then I'm going to hit the enter key on my keyboard which was the wrong move then I'm going to hit the tab key on my keyboard and I can change the name of the array now. Everywhere the word array is used I can swap that out with the letter A for example tab key one more time here it puts me to another replaceable area for the element and here I'll use C I'll use tab one more time and then it kind of exits me out of that snippet replacement structure and now I can continue on and type like console.log and we'll just print out C ok so let's grab A from our previous example and then we get the same results we got before but this time we didn't have to memorize exactly how to use for the code snippet walked us through and allowed us to replace the names of the various replaceable areas like the name of the counter, the name of the array and the name of the given element C that we extract out of out of our array ok just comment that out that's four and now let's take a look at the while loop so we'll talk about the difference between these it may not be obvious at first but essentially we'll do this alright so take a look at this knowing what you know about loops what do you think is going to happen here well we start off with one and we're going to continue to execute this loop until this condition is false so the very first time we run it one is indeed less than 10 so we'll continue to run the body the block that's associated with our while statement and we'll print out the value of X and then increment its value by one we'll continue to do this until we increment the value of X and it becomes 10 at which point this is no longer true it becomes false and then we'll break out and continue on so let's go ahead and see what value what the value is that we get so we get one through nine that's expected and once we hit 10 we break out great alright so what's the difference between the while statement and this first for loop that we did here at the very top well the difference is that the for loop first of all has a lot of infrastructure that we have to build these three pieces and it uses a series of indexes that represent the number of iterations that will move through this block of code now the while statement is a little bit different anything can be used to drive the iterations as long as this statement continues to be true we'll continue to execute this block of code and so we control the number of iterations in the body in this case here I do the X plus plus now we don't have to use counters we could use anything any kind of business logic like we may want to read to the end of a file and once we hit the end of the file it no longer it makes sense to continue to read each line of the file then we would want to break out so the while is a little bit more flexible and so much that we can build the business logic for how many times we're going to iterate in the body of the the while statement whereas with the for we're pretty much limited to the number of times we want to run this being the number of times that we've kind of preset it up here in this top section outside the body itself okay now there's also one last thing we can talk about and that's a way in both the for and the while we can kind of circumvent this check right here and we may want to do a check like this so if X is equal to 7 then we'll call the break statement alright so learning what we've learned about the if statement it probably should look more like that right so let's first of all let's make sure it works in this case we got 1, 2, 3, 4, 5, 6 once we reach the 7 we circumvent this check and just say hey I want to break out of this alright so we can use that always to break out just like we broke out of the switch when we wanted to not flow through additional cases now the one thing I will say if you notice how I type this to begin with let's retype that so hold on let me comment this out so that you can see it in the code if you want to download my code but we could also do it a little bit more shorter and in line since I only have one statement that I want to make right after the if statement I can do it on the same line and I don't need to surround it with a code block a code block indicates there's usually more than one line of code in this case there's just one line of code I could put it on the separate line and use some indentation like that or I can just keep it all in the same line since it's so short but that might improve readability or I might decide that this is a more readable form that's kind of up to me and if I'm working on it with a team of software developers I might want to get and kind of do it the way that they do if it's stylistic for me this is so short I can read it all one shot if x is 7 then break out of it it just it looks good it's very readable I'll be able to understand what I'm doing later on it doesn't take up and move the code down so I like that that format if I just need to create one statement right after my if right after my if so sometimes it makes sense to split things on separate lines sometimes it makes sense to keep two different statements in the same line again I think it kind of is a stylistic choice that you'll you have to make for yourself at some point alright so that is iteration statements we looked at two different kinds and we looked at how code snippets can be used to help us remember the format now I believe the while has in fact I believe most of the things that we've looked at has some some code snippets available like if I find it here in Intellisense enter on the keyboard but there's not as much to it there I mean while with the condition I can change this to x is less than 10 right it's not so much for me to type that out but the four makes a little bit more sense because there's so many parts to it and replaceable parts of that okay so let's continue on the next video we'll see there thanks it seems like quite a while ago we talked about variables but now that we're working with blocks of code inside of blocks of code like we had here in lines number 23 and then 29 through 31 we need to talk about variable scope and when I use the term scope I mean variables are a little bit like people in so much that variables have a lifespan they're born they do work and then they die and they're removed from computers memory when they go out of scope and we'll see an example of that in just a moment but they're also like people in so much that they have a citizenship I guess you can say in other words depending on where they were born they can work inside of some code blocks but not other code blocks and so the remainder of this video we're going to look at lifetime and availability or citizenship I guess you can say inside of the rest of your application so let me create a new file and we're going to call this scope basics and there will be more to say about scope as we move forward and learn more about functions and so on in just a little while here but let's start and create first example here so let equals first then I'm going to create a function called scope test and inside here I'll just do a console.log and the first thing I want to see is if I declare variable out here outside of my function can I reference it inside of my function and so to find out let's just call scope test and see what we get so here we're going to type node scope basics and we can in fact view the value of a variable that was declared outside of the scope of a function we can view it inside of the scope of that function so the next thing that I want to do is to say hey let's create a variable here now if I create a variable inside of a function scope can I view it out here outside of the function scope so console.log B and let's see and so no not only can I not see it but my application actually blows up and you can see the little carrot here is right underneath the B and it says B is not defined so in other words you can kind of think of it again in terms of the lifespan we created a function created a variable inside of that function that variable lives as long as that function is running but after the function after that code block has completed executing then B is removed from the computer's memory and essentially thrown away therefore we cannot reference that variable outside of the function because it no longer lives it's dead alright so we're going to have to comment that out and we can go ahead and comment this out as well now let's do one more thing here let's say if A and we'll just do something silly here if it's not equal to an empty string so just two single quote marks next to each other so then can we still see the value of A even inside this innermost block of code that we defined with an if statement if we can we should see then it printed here a second time the value first so let's say what we have let's run this again and so we see first first the first time is printed out and the second time that is printed out alright so yes if something is declared in an outside scope it is visible or it can, it has citizenship in every inner scope from that point on but here once again if we were to create a variable third and then try to reference it outside of the code block in which it was defined like so will this work what do you think we're gonna get that same kind of error before we get the little arrow pointing to the C and it says that C is not defined the variable C was defined inside of this code block and once we executed that code block and got to the end of it then C was removed from the computer's memory it's no longer available to us in a sense dies and it's no longer available okay now let's just do one last thing here just to kind of understand that we are in fact able to work with the variable that was defined in the outermost scope can we still work with it use it and change its value so I'm gonna change this to changed and then I'm going to reference it here console.log a and so now let's run our application one more time alright so the first time that it's run this first console.log it will be the value first then we change the value and we log it again and that's where the second change comes from after we've executed that function then we execute line 20 and that's where this third changed appears alright so I guess the moral of the story once again to kind of reiterate what we said when you declare a variable you have to understand in which scope it was defined because based on the scope or rather the code block in which that variable is defined it's going to have a lifespan and it's going to have citizenship if it was defined in the outermost scope it will have its life and its citizenship in all interscopes but if it's defined in an intermost scope it will not be available to outerscopes now one last thing and I'll kind of end it right here we were to take and this is probably just a question for you just thought question if I define b here right above that if statement and then I attempt to use it right here and call this inside if do you think that we'll be able to reference that value well based on what we know about the rules I would expect to see the value second printed out so let's try it and in fact we do see it so hopefully that supports your new understanding of the scope of variables defining them outside of a code block versus defining them inside of a code block and trying to reference them outside ok so hopefully that all makes sense we want to make sure you're clear on that we're going to revisit the topic of scope because there's a lot more to this but this is your first introduction so that you kind of understand what the rules of scope are at least in the most basic sense alright so we'll continue on the next video see you there thanks for the topic that we'll keep coming back to over and over throughout this course it's important because at least when your javascript is run inside of a web browser you must be aware of the top most level of scope which is referred to as global scope in node like we're using here it's not as much of an issue they've got some safeguards against it but in web development working against the global scope is a crucial concern a lot of consternation and consequently a lot of effort has been exerted to preach that declaring variables at the global scope is a bad idea so you would never want to do something let me create a new file here returning functions.js js there we go you never want to do something like this note the use of the var keyword and you never want to do something like this although you're more likely to do it than the previous line in line number one now the reasons why you would never want to do that this will require a little bit more explanation a little bit down the road and I'll make this point emphatically when we start writing javascript for the web browser later on in this course but for now just understand that much of what I'll say and why I say it over the course of the next 5 or 6 lessons or so we'll be working towards a solution to avoid writing your code in the global scope if at all possible now the eventual solution that I want to demonstrate relies on how javascript functions work but we need to take a few baby steps to get there so the first aspect of this technique that I want to demonstrate has to do with returning a function from a function now up until now our functions perform one or more actions and then exited quietly we may have returned a simple value like true or high or something along those lines however we can create functions that can not only perform some action but then at the very end can return a value to the caller and not just any value can return a function so let me comment all this stuff out and I'll say don't do this to make sure you never do that and this either and then I'll just do a multi-line comment here and so let's start off really simple this is something that we've already talked about when we talked about declaring functions or function declarations so here's function 1 let's return the string 1 it's not very exciting but it demonstrates the point that you can use the return keyword to return a value to whatever calls that so for example let value equals 1 for example and what would we expect to be in our variable value well we would expect to print out the string O and E or 1 so console.log and value like so and just to see this working let's go ahead say node and then returning functions and we see it returns here at the bottom of our screen the string 1 as we hoped now we could also kind of paraphrase this make this a little simpler by just doing it all in one line right so we could put the call to the function and not use a variable call to the function which returns a string and that returned value will automatically be passed into the console.log method let's save that hopefully that makes sense and that's a common technique that we'll want to use but things start to get a little bit more mind bending when you start to think of a function as just another data type in javascript so for example let's go back to this I'm going to copy this again and then let's go to console.log and then type of value and well let's do this let's get rid of the method invocation operator so now we're just setting a reference called value to our function 1 let's see what we get and you can see the type is function so let's think about all the data types we know about now we know about string we know about number we know about boolean we know about undefined and we know about function right and we're going to learn a couple more before this is all said and done but at any rate notice here again I'm just in fact we could even do this a little bit differently I may have muddied the waters by introducing a variable let's just do that instead and we should get the same the same result so I guess the heart of the matter here is that we can get a reference to a function and we can store that reference to the function out in a variable which means we could also do something like this so now we have a reference to the function we can call the function using the method invocation or the function invocation operator so let's go ahead and run it I guess we need to actually then go console.log there we go now we're getting somewhere there we go okay so hopefully that makes sense I just have a variable pointing to the function and then now that I have a variable pointing to the function I can execute the function by just using that variable with our method invocation operator right alright hopefully you're still with me so far hopefully this isn't too mind bending let's continue on here so since a function is just a data type like any other data type that we've learned about so far our functions could return a function because we're just returning a value and that value can be any type so in other words let's do this function2 and here we're going to return a function now this is a function expression inside of a function declaration right and here console.log and 2 and then do something like let my function equal to now what gets returned to my function it'll be this enter function expression so I should be able to do something like my function with the method invocation operators and let's see what we get and we get the value 2 like we'd hoped alright so hopefully you can see here we're using the return keyword to return a function expression we get a reference to that function expression by calling the outer function declaration now we have a function in hand or reference to that function this inner function right here and we merely invoke it hopefully all that makes sense and we might be able to do this a little bit differently let's try just a slightly different tact so here I'm going to go function 3 and here I'm going to return function and then return 3 alright let me spell return correctly alright so in this case I'm returning a function that returns a string so I should be able to do something like console.log and then I'm going to call 3 what do I get back from that I should get back a function so I should be able to invoke that function to get back the string to get to the console.log now you would never do this and you would never see this but this is just to illustrate a point that of what you're really working with and that's references let's actually execute it there we go 3 what you're working with here are references to functions that can return references to other things and maybe even other functions right so again that last one is pretty far fetched you probably never do that but the fact is that what gets returned from our 3 function declaration is a function and then it can be invoked with the function invocation operator here the second set of inner parentheses right there so on the surface this might not seem like a very significant development in our javascript journey but nothing actually could be further from the truth because this is actually a huge step towards moving our code out of the global namespace like I talked about at the beginning of this video but to complete this story again we have several more baby steps to go we're going to need to step away from functions for a little bit and come back to them once we've learned a little bit more about arrays and objects specifically so just keep this thought in mind and we'll continue on you're doing great, hang in there we'll see you in the next video, thanks if you remember when we were looking at arrays I did the type of on an array and it returned back the word object so that's actually another data type in javascript and until now obviously given the title of this lesson we're going to look at objects so an object is similar to an array in some ways but its intent is dramatically different an array will hold a list of information in other words there may be many data items whether they're strings or numbers or booleans or even objects each stored in a different element of the array contrast that to how an object works an object contains the related properties of a single data element so array, many data elements an object one data element but has attributes so the settings of the properties define the characteristics of the object so let's say for example that you want to have a car and so an array will only really let you save maybe the year of the car or the make of the car or the model of the car as a string or maybe some identifying number but an object would allow us to define all of those properties kind of in the same container so you know if you try to keep track of all the properties and maybe even all the methods that belong to a car but you keep them as separate variables and separate functions you'd run the risk of clashing with other variables and functions that have the same name for a different car okay but objects let us keep that information kind of safely locked away in their own little container where the relationship between all those properties and functions are obvious that they all kind of belong together to describe one car and then you might have another object that describes a different car and you can keep both of those objects those two cars in an array of cars so hopefully you can see the relationship between those alright so let me first of all start out by creating a new file object.js and so I may have an object that has a series of properties that describe a specific car and I might want to for example keep track of the make the model and the year and so on but I may have some functions that I need as well things like getting the price of the car based on some criteria maybe you know the year of the car and things of that nature and I may want to print out a special description of the car that includes many things like the make the model of the year in a special format but I might define a car object like so so let's do let car equals define an object using a a code block so curly braces now I'm going to use kind of a name value pair here so let me just go ahead and start typing alright take a second and catch up with me there you like now let's go ahead and use the print description function like so and let's use the year property like so I'm going to save my work and then I'm going to type in node object and the first print out is BMW 745 Li because we're printing out the make and the model of this car alright and then here I'm just getting the year of the car and printing that out in a console window alright so in this case this object that I built on screen we're dealing with a tangible real-world and very relatable concept that of a car we've all driven in cars or have driven cars in your JavaScript code you'll occasionally be working with objects that define tangible real-world things like cars but you're also going to work with things that represent more abstract concepts that are specific to web client or web server development so in this sample I created an object using what's called object literal syntax so I literally want to create this object and then I'm going to assign that object to a variable named car and the body of the object is like I pointed out defined with a series of curly braces here this set of curly braces at the outermost level here this defines kind of the boundaries for the objects and everything that lives inside of it either a property of that object or a function called a method inside of that inside of that object so let's start off in lines 3, 4 and 5 here we have a list of name, value, pair so here's the name of the property and here's the value of the property in this case notice that each of the names of the properties are just identifiers they're just like variables in fact I want to use the same naming conventions that you would use inside of with a variable and then the values can be any data type in this case I have a literal string BMW a literal string 745 li and a literal number 2010 that represents the year and notice that the property and the value are separated by the colon character and then each property definition as well as each function up until the last one are separated by commas now I put each of these properties and functions on their own line or series of lines as it might be for the functions in order so that we can see some readability but that's not entirely necessary from JavaScript's perspective it would be fine if we put all this on one line of code alright so again with regards to the names of both properties and these functions which I call methods you'll want to use the same naming conventions that we used previously when we talked about variables now there's some other ways to create objects and I'll discuss another technique in one of the upcoming lessons so we'll come back to that notion because it'll lead into another discussion that kind of takes us off at a whole other tangent that I don't want to go on right now so here we define the function kind of the same notion I gave it an identifier the name of the function that I want to access and then I'm using a function expression and define the function expression within several lines here but essentially we're just returning a value or in the case of the second one just calling console.log we could write any number of lines of code inside of here these are just happened to be very simple for the purpose of illustration alright so I've defined my object now I want to actually use it and reference it, how do I do that well you can see that whenever I wanted to access a specific property of my object or when I wanted to access a function I use the variable name that I set the object reference to and then I use the period on the keyboard which I call the property access operator just the dot on the keyboard same as true in accessing the function as you can see here in line number 15 I use that period that member access operator and then all else is fair this is a function so I'm going to use the method invocation operator just like I would to invoke a normal function now I keep referring to these functions that are inside of an object as a method I can probably start referring to functions defined inside of objects as methods it's a more descriptive term and I'm already used to it for my work with other programming languages but simply put a method as a function that belongs to or rather is defined inside of an object now there's another syntax that I could use in addition to what you see here and it opens up some interesting possibilities that I'm not very fond of but you could definitely do something like this so it almost looks like I'm using the array array element accesser to access a specific property here let me go ahead save that so we'll see the year appear twice here if all goes well and we do at the bottom so that's one approach to accessing an individual property and the other is similar but it uses an index so it's actually kind of interesting how this works what is the the fur or index one of my car let's find out the hard way here and it's set to undefined in this case so actually it doesn't reference any of these it basically creates its own new property and sets its value to undefined let's never do that let's not do that I prefer the dot syntax again it's going to be most familiar to those of us coming from other programming languages but you could in some advanced scenarios use these techniques to do something a little more advanced and that's way beyond the scope of this lesson I recommend you just use that dot notation for now it's going to be pretty happy so you can do like I kind of mentioned a second ago some pretty advanced things with objects and there's a lot of room for variation so I recommend taking a look and taking notice of how other people work with objects in their javascript code as you're perusing the internet because there's always seems to be a new twist I think I understand how objects work and then I'll see somebody do something really extreme and interesting and I'm like wow that opens up my understanding of how objects work I'll just give you a quick example of what I'm talking about here here we can create another car and I can create an empty object like so and then I don't have any properties inside of my another car how do I reference another properties inside of that well what I can do is just kind of just say hey I want to create a property here called whatever and I'll set it equal to Bob alright and it will just automatically create a property called whatever and set its value equal to Bob just like that no lat or var keyword or anything if I do console.log you'll see that car.whatever in fact will come out to be Bob or I thought it would I think what I'm going to need to do is save my work here and then do try this again I'm sorry another car I had the wrong reference it didn't exist on car but we need to look at another car.whatever and there we go there's Bob okay so just an interesting feature of objects you can add properties kind of ad hoc and some people do that and that is kind of a feature not really a bug of javascript it's dynamically typed you can just say hey I need a property here I need a function here and you attach it to an existing object and there it is it's you've got an object now with this additional property called whatever alright you can also do some other kind of interesting things might as well take a few moments and look at these so I'm feeling unoriginal now so I'm going to create a new object called a and inside of this I'm going to create my property and I'm going to actually set that to another object I'll define a property inside of that and I'll just say hi because again I'm feeling rather unoriginal and so let's figure out how can we actually print out the a so console.log a.myproperty.b will I get what I think I'll get I will so you can see how I can chain things together whether they be functions or properties by just continuing to use this is an object that has a property that has an object that has a property and so I can kind of chain through and create essentially what becomes a namespace and we'll reference that a little bit later when we talk about evolving the global namespace issue or putting our variables at the global level of our applications which we're trying to avoid let's take a look at another quick cool example of things you can do with objects that might not be so obvious at first glance so here I'll create var c and inside of that I'm going to create another my property and this time I want to create an array so this property the value of my property now will be an array of I could do strings I could do numbers but I could do an array of objects so and that's perfectly valid so here think with me again I have an object that has a property that contains an array of objects that each have different properties alright and that's perfectly valid objects can't contain properties of the type array that can contain other objects that can contain well really just whatever makes sense for your application however you need to store it and kind of represent the data that you're working with also if you're going to work with an array of objects it might make sense for all of them to have the same set of properties like in this case each object has a different property I'm not so sure that would be so useful but it might be something that you need to model in your application forcing you to keep the same set of properties for any given object inside of an array of that object you know as long as your javascript code or whatever will consume this object understands how to interpret it that's all that matters so once you get past the simple hierarchy of values you typically refer to something like this that gets a little more complicated as an object graph a graph of objects just keep that in mind let me paste in some more interesting examples here just kind of expand your thought process and how to work with objects let's say I have a car lot and I want to store an array of objects each object has your make and model then I could iterate through the car lot and print a screen each of those all car objects so that's one example how about if this was more of a I guess you could say a system that kept track of all of our customers and employees we might do something like this this gets a little more complicated and unfortunately it runs off the side of the screen a little bit but you can see here I'm creating a contacts object here's the start and the end these are called customers and a property called employees now both of these have as you can see an array of objects and these objects look very similar and so much that they have a first name, last name and then phone numbers and then phone numbers actually is an array of strings in this case this particular what is he a customer this customer bob taber has two phone numbers and then but our employees like Steve and Conrad Grant well Steve has two phone numbers but Conrad Grant only have one phone number so you can see that things can get pretty crazy really quick but that's a perfectly valid object initializer it just happens to be a little bit more complex than the ones that we started off with so now as you're looking at this you might think to yourself wow this this actually looks similar where have I seen this before it looks a lot like Jason have you heard of Jason J-S-O-N or Jason I guess some people put the emphasis on the on that's short for JavaScript object notation Jason is both descriptive and compact and it's probably the most popular way to send information between two disparate systems so we might in fact use it to store settings or properties inside of you know a more advanced JavaScript application or use it in Visual Studio and C-Sharp projects to store application settings for example now in the new version of C-Sharp and .NET we might use it in our application sooner than later to send data between a single page application that lives on the client and the backing web API that on a web server that hosts a web API if none of that made sense don't worry about it eventually you'll get to that point if you continue on learning JavaScript what was my point here if you're familiar with what Jason is you might notice that there are a lot of similarities between the object literals that we've looked at in this video and Jason however there are some subtle but important differences between the two and I'm not going to take the time to go through that you can easily do a quick search online to see what the differences are between object literals and JavaScript and the JavaScript object notation or Jason where that these are not one in the same there are subtle differences you cannot use them interchangeably but their syntax is very very similar and Jason or I'm sorry JavaScript has a built-in function that I'll let you work with Jason as you might expect okay wow I've really gone long on this one but objects are pretty important and we're going to use them a lot and there's a lot to them in fact we're probably going to be talking about them a couple more times before the end of this course maybe even in the very next video so you're doing great, hang in there we'll see in the next video, thanks previously I said that much effort and education is centered around the dangers of defining variables and functions in the global scope also referred to as the global name space especially when writing JavaScript that will ultimately be targeted at running in a web browser but I never really answered the question is it dangerous? I never kind of ventured into that and I'm going to illustrate more clearly later on why this is dangerous and how you can really hurt yourself when you are creating variables and functions in the global scope but in a nutshell the global scope is global so number one each variable that you define in the global scope is not removed from the computer's memory until the web browser or the tab of the web browser navigates to a new web page so the more that you add into that global scope the more memory you're taking up and that memory is consumed the entire time that that tab is open for that particular web page but more importantly number two again emphasizing that this is the case with JavaScript in the web browser not so much true whenever you're building node style applications as you load JavaScript that you wrote and you rely on JavaScript code that others write whether that be code that JavaScript libraries that you've downloaded from the internet or that you include your project somehow maybe they're ones that other people in your company have written and you need to include them in your project or perhaps even sold commercially online some product that you purchased came with a JavaScript file and you include it maybe it hasn't been updated in a number of years the variables and the functions that are defined in those files when you consider the variables and the functions that you've written in your files there's a the more that you write at the global scope the more that they wrote at the global scope if they didn't take precaution the more likely you're going to have a collision of names at some point somewhere down the road somebody's going to have a variable named what you named and they're both trying to contend for the global for being the variable the winner in the global scope so we call these naming collisions and when these naming collisions happen either your data will get overwritten by their code or their data will be overwritten by your code but either way undoubtedly it'll cause unanticipated bugs that are difficult to track down and quite frustrating and the reason why this is even a thing is because it's happened okay so now that it's happened everybody is extremely concerned about it and so a series of suggestions came out and a lot of effort went again around trying to figure out how to solve this issue given the tools in JavaScript that they had available and the first one that has come out and that I've recommended from the very first lines of code that we've written is to use the let keyword instead of the var keyword because the var keyword will attach variables to the global scope which in a web browser is the window object in the document object model we'll talk about that a little bit later and it's also recommended that you use the technique the design pattern that we're going to discuss in this video whenever you're writing JavaScript code or there's a third option which is new in JavaScript in the latest version of JavaScript called modules unfortunately and I may even talk about this at more length later on the implementation of modules is a little bit uneven between node and the web browsing environment so I'm not sure how helpful that would be at least as we're getting started and learning about JavaScript just keep in mind there's several different attacks but this is probably the one that you'll see used most often in at least JavaScript that's been written over the course of the last 5 to 10 years but there are some newer ways to tackle this. Alright so anyway the technique that I'm going to discuss in this video or the design pattern actually uses a couple of techniques that we've learned about so far we're going to use an iffy remember what that is an immediately invoked function expression to create a function and then that function will return an object and that object will have defined functions and variables that will then be kind of scoped to one variable so instead of having 5 or 10 variables that will have only one variable in the global scope or at least in some scope and then we'll be able to reference the individual variables and functions of that particular object that gets returned. Alright so we'll see how variables and functions can be made essentially private so that we can hide some implementations from the ability for just any code to call them this is often called encapsulation in software development terms and so these will be unavailable outside of the public variables and the public functions that will return and that's generally a good thing so there will be a couple of benefits that come out of this alright so let's get started by creating a new a new file called module pattern.js alright so let's start by creating an iffy and to do that hopefully you remember how to do that we're going to start with a function expression we'll just create an empty one we wrap it in a set of parentheses and then we use another set of parentheses to actually invoke it alright so what I'm going to do before we get any further is actually set this immediately invoked function expression to a variable I'm going to call this counter so I'll set counter equal to whatever is returned so eventually what we're going to do here is return an object full of properties properties that have values properties that point to functions that can be called but we can also do some private stuff here and this will not be accessible outside of the calling the counter dot something to access it and so we can like have a private variable here like let count equals zero and we would not be able to do counter dot it just wouldn't be accessible we'll fix that here in a moment when we return an object will give an accessor to it will take a couple of passes at that actually okay so let's go and create now a private function as well and this will just print out a message and style it up a little bit differently so we won't get crazy here so console dot log and we'll just say whatever the message is and then we'll just do like three dashes like that just a little bit of style just to show that you know we have something here that could be private but now ultimately what we want to do is return an object that will be at set to counter here so we're going to start off simple we'll come back to this a little bit later because there's going to be an issue with one part of this actually this part right here what if I just want to return back the counter the current value of or rather the current value of count I can try that again we'll come back to that in a minute but let's say we create like an increment increment property and it will return a function and inside that function we can do something like count plus equal to one and then we can call to our print method and then just say after increment something like that we can also and here let me use comma right there because we're going to create another property of our return object called reset and what this will do is call a function so we'll create another function expression print before reset then we'll call the count and then print or we'll set the count equal to zero because that's the point of a reset and then after reset it should always display zero but let's just double check that alright so now we have basically our our module pattern we created a module which is essentially an iffy that returns an object that will expose functions and other properties like like the current count and now here because I've invoked this immediately this is available it's already been executed and counter now is fully populated and ready to be used in our application so I can do counter dot um value I think wasn't that the name but I've forgotten everything already okay have value so console dot log counter dot value and um I could try to do console dot log counter dot count just to prove that it won't give me anything back so let's just start there and we'll go node module pattern and uh first time we get it undefined wide because count is not a property of counter uh because we didn't it's not exposed and it's not being returned in the return object alright so that is impossible now what we can do however we will try to do is call counter whoops counter dot increment you can see it shows up in intelligence that's a good sign uh so we'll call increment in fact let's call it like three times whoops below where I want to go there alright great and then we'll call counter dot reset like so alright so let's see what we get this time it's not going to quite be a satisfying uh because we're going to get a little issue on on uh on these lines here so you can see after the increment the value is one two and three but then when we attempt to get the value of counter from this property count we would assume it would be three right but it's zero what happened here well we accidentally created something called a closure and another little topic we need to talk about in JavaScript so let's not do that we're going to need a different way to implement this basic functionality so can't use this technique what we're going to need to do is take a different tact and we're going to implement two more functions here we'll create a set function or I'm sorry let's start with a get function and get something super simple it's just going to return count and then and I did it all in one line put it done on multiple lines to need to it's pretty simple function and here we're going to set count equal to some value that's going to be passed in so here we'll say we'll accept an input parameter called value making sure we add some commas in between these new properties here that are set to these functions we'll take in some value and we'll set count equal to that so we should be able to come down here and now since we've kind of removed that let's go counter dot get or actually let's set it to the value of seven here we'll do a console dot log counter dot get to ensure that it is seven and then we'll call our reset let's see what we get when we run it this time alright this is a little bit more interesting well almost interesting I need to invoke get I forgot that save it run it one more time there we go okay so here we go lines 33 through 35 will produce these three lines where we're after increment one two and three then we call counter set passing in the value seven and so we then do console dot log get counter get and we get that seven back out now we call reset and before the reset the value will be seven after the reset we reset it to zero okay so hopefully you can see that this technique of returning an object from an iffy will first of all allow us to keep some implementation details private like we couldn't get to count and we didn't try but we wouldn't be able to get to print because only certain things are being returned and mostly in in terms of functions that give us access to the private functionality and a little bit more but in addition to that we've reduced think of all these variables that we've reduced out of the global out of the global scope there's no count variable now there's no print there's no get set increment or reset they're all part of this one variable called counter and so there's less of a chance that we're our namespaces are going to collide as a result of that now we want to pick something unique there maybe something that describes a little bit better what the intent of this is maybe something specific to our brand or company and maybe pick something fairly unique there but as a result of that we've protected ourselves and written our code a little bit more defensively now there's one more thing that I want to talk about here and that is that okay so keep in mind this this technique that I've just demonstrated here is so popular that it has a name this is the module pattern there's another variation that was created on this called the revealing module pattern you might see this used as well let's go ahead and create another file and I'm going to call this reveal revealing module .js alright and I'm just going to paste some code in so that we can kind of compare and contrast the two versions alright so it's very similar in so much that we have an iffy that we've defined inside of that iffy we have some private stuff just like we had before here we have some more private stuff these are the implementations of get set increment and reset but I've created these as function declarations with names now here at the bottom we have this is the revealing part of the revealing module pattern here I'm revealing publicly accessible functions by including them as properties in this return object so I can call counter.get and counter.set exactly the way that I could before but behind the scenes they're calling the implementations that are defined here and so there's a couple of benefits and a couple of downsides first of all what makes it a revealing module pattern is that it reveals the public functions through these properties in the return object okay and it's a cleaner, clearer presentation of what actually gets returned but there is a downside and that is you can accidentally overwrite these are just properties so I could set the value to get equal seven and not and forget the method invocation operator and as a result I can pretty much just break the association between get and the function name getCount and so that's a downside we could accidentally break this whereas in our module pattern you can't really do it that's not possible okay so that's the module pattern the revealing module pattern it brings together a bunch of techniques we've learned all to the greater good of removing or reducing rather our impact on the global name space by removing variable names and function names from our from the global scope okay and we'll see why that's important on the web development side of things as we move in that direction but wanted to kind of bring all that to a head alright so let's continue on in the next video see there thanks as you're getting started closures can be another mind-bending topic in JavaScript but they don't have to be if you understand them you can really unlock the power of JavaScript having said that personally I don't rely on them very often when I write code but I'm not a JavaScript ninja so your mileage may vary you're going to see a lot of articles and tutorials out there that talk about closures and I think sometimes they make things more difficult than they really need to so I hope to provide a really simple explanation that will simplify this topic for you and you can get into some of the more advanced stuff a little bit later on but basically a closure allows you to associate some data with a function and then use the function with that data already kind of baked into it from that point on in my mind it's kind of like this I'm basically taking a function and I'm marrying it to some data through an input parameter and input argument and then they live happily ever after in their own variable and from that point on they work together as a team whenever I want to invoke that function with that data already pre filled I guess you could say into the input parameters I can call that new variable alright that's all it is and well okay there's more to it than that but for the most part that's all there is so let's just create a really simple example or two and hopefully it'll clear some things up so let's create a new file called closures.js and let's start with just a function I'm gonna create something super simple say hello and then inside of here I'm gonna return a function that's kind of the point of this and it'll just say howdy and I guess we're gonna pass in a name so howdy plus the name alright alright so that's really step one I create a function that returns a function looks like I got a little problem here whoops I return a function there we go so here's the function returns a function and I'm passing in a argument called name that I'll ultimately use in the body of this return function alright so then I can actually make a call so for example let Bob equal say hello and passing in Bob now from this point on I call Bob well we'll see what happens here node closures alright howdy Bob alright so by itself it isn't all that impressive but that's really kind of step two and three all in one shot and some variable that slightly modifies the way that this return function operates so in this case it's pretty simple I'm passing in a name and it will change what gets printed out every time whenever you call this function in the console dot log alright so this value is basically saved off in a variable outside of the returned function so we're relying on how scoping works in order to get that closure behavior that name kind of follows along this return function everywhere it goes Bob gets passed along from that point on and then this is step three where I save that off in its own variable so that I can call from that point on and I kind of get this say hello with Bob prefilled right so I can do the same thing with Conrad say hello and then grant say hello and that's all a closure really is so let's those and there you go three versions of the same function that get returned we modify the operation by taking advantage of how scoping works in JavaScript by kind of giving it this value that it's going to hold in its own context from that point on in stored in these separate variables alright so this is really the binding process that binds these together and then stores them off that's all it really is so another way to look at this the say hello method has finished executing and it returns a function but in the environment in which the method originally ran it preserved that whatever value we passed in is preserved inside of this return function the environment or in this case just the name input parameter this variable name remains available so now in step 4 I guess you could say if there was a step 4 I basically use the new variable which represents a call to the method and a preset input parameter conveniently call that version of my function now so the important lesson to take away is that each closure creates its own what's called lexical environment and you'll see the term lexical used a lot in JavaScript whenever you're learning about scope I try to steer away from that term because I feel like maybe it clouds the issue a little bit it's basically just a fancy word for everything that we learned about in the scope basics here previously where if you define a variable outside of a function it is available inside the function but if you define it in a child code block essentially it's not available outside of that child code block so that's basically what I mean by lexical scope it basically defines how a parser resolves variable names and functions when they're nested and the word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available from that point on throughout the rest of your code so nested functions like we have here in our say hello that returns a function have access to the variables that are declared here outside of it as well as any of the input parameters that are declared outside of it and outside of their original scope and that's just how the lexical rules work like we learned about in scopebasics.js so when we create a closure each closure gets its own lexical environment meaning that they get each time we create one like we do here in lines 8 through 10 they get their own set of variables their own name variable and anything else we were to define outside of the function in this case we don't have anything else and there's more to closures you can get in some pretty advanced scenarios they're a powerful concept in javascript the ability to retain or bind to the lexical environment of the variables that enclose the returned function like in lines 3 through 5 to create a version of the function with some values already pre-applied is pretty powerful if you don't completely understand that that's okay don't get discouraged for now just understand that whenever you return a function from a function you also glue any of the variables that were defined outside of the return function including in this case our input parameters alright that's all you need to know about closures well for now anyway alright so let's continue on in the next video you're doing great see there thanks if you think back to the lesson on object literals I think we were working in the object.js file I created a car object with several properties and functions and you can see that I created a new file called this-keyword.js if you're pausing the video to follow along then you might want to go ahead and create this-keyword.html yeah that's right we're going to write some javascript in an html page for the very first time in this course here in lesson number 18 because I want to show you how this works in different contexts that this keyword but getting back to the point at hand if you recall that example that I've pasted in from that object.js file into this keyword.js you'll see line number 10 and at the time I didn't even proffer an explanation as to what the this dot make and this dot model actually mean in our in our application the fact is that this keyword can be a little bit challenging so even people with a little bit of javascript experience from time to time get a little confused about the this keyword and one of the reasons people get confused about it is because it means something different in javascript than in most other programming languages so you actually have to kind of fight your existing knowledge so if you're coming from another programming language the best thing you can do is kind of just leave everything you think you know about job about well a lot of topics but in particular about the this keyword at the door and if you are just coming to javascript as your first programming language then you might even have a slight advantage here because you won't have to fight yourself in what you think you know but simply put the this keyword in javascript represents the way a given function is called the way a function is called will determine what this represents okay so you essentially bind the this keyword to a given context and we'll explain what that means based on how you call the function alright so up to now we've not really paid much attention to how we call functions I told you there was really only one way to call a function using the method invocation operator so we would do something like this a little bit later on right like a card dot print description alright and I used the method invocation operator and I didn't even hint to the possibility that there would be another way or multiple ways to actually invoke a function but that's actually pretty important when you consider what the this keyword represents alright you're gonna learn in this video at least that there are other ways to call a method that allow you to set or rather bind the this keyword to something so that you can do something interesting inside of in this case your object or your function or whatever the case might be now you may never need to do this but it's important to understand the basic rules and how that this keyword gets bound to a context and gets referenced inside of your object or your function there's an entire book written about how this functionality works and all the permutations and it's awesome it's a little bit over my head at times so I'm gonna give you an absolute beginners explanation as to how this all works but it should serve you well as you're getting started and then you can refine your understanding a little bit later on but let's start out and by commenting out everything and you know what there's a really easy way to comment out everything that I haven't talked about yet alt shift and a on your keyboard will add a beginning and an ending code comment character operator to whatever you have selected so that's a nice quick way to do that great so let's start really simply I'm just going to create a function called first and this function is going to return the value of this what is the value of this well here if you go console.log first is it equal to the global object inside of node so the global object we'll talk about that a little bit later I guess it is kind of the most basic context of things that get executed inside of so when we create something in the global namespace and global variable we would create it essentially attached to the global namespace it's available everywhere in our application alright so if when we call first from line number 20 is this which gets returned equal to the global the global object so let's go this dash keyword and it is true alright so when I call the first method basically from the global context because I haven't created it inside of using the module pattern inside an iffy remember what we talked about previously so I'm basically just calling this here out in the global namespace and what gets returned back is the fact that this is equal to that global namespace alright so now let's try something else actually let me just do this let me copy this little comment that I have in my notes because it might be helpful to you for reference alright so let's start with another code example now function second and the only purpose of this is just to show that there is this little flag called use strict there's a strict mode in JavaScript we're not going to go into it much but this will change how um this keyword is bound and so if you have use strict turned on and you try the same thing that we just did here, let me comment all this out using that alt shift A technique and we essentially do the same thing here where we go console.log and then um second equals global let's see if we get what we think we're going to get from the first time around false alright well I happen to know that it will equal undefined and that is a true statement what gets returned from this when we use use strict is an undefined uh value it gets bound to essentially nothing alright so just keep that in the back of your mind this the rules around binding the this keyword change depending on the context in this case the context is use strict it will fundamentally change how it works so with that out of the way let's move on to the next example here let my object equal and I'll create a property called value and set that to my object and then I'm going to use the this um create a global variable called value and I'm going to set it on the global object by doing this global dot value at this point I've created a new property on the global on the global object and I'm going to call this global object alright again in node this has special significance if you're doing web development it's actually window and we'll look at that here just a little bit alright um so now let's go function third and we'll return this dot value and then we'll do a console dot log third so by default what do you think we'll get printed out we print out the value of the global object which I set to the string global object or the value of my object which is set to my object well hopefully based on what we learned in this first example you already know where I'm going with this and because we called third from the global namespace when we reference the this keyword it's referencing this global variable so when we grab the value property it's grabbing the value property of the global variable thus printing out global object let me show you that there are other ways to actually invoke the third function and we can control the binding of the this keyword like so so here we're going to console log and then I'm going to call third but I'm not going to use the method invocation operator I'm going to use the call method or the call function of the third function alright so it has a built in method called call and there I can pass in my object and this is how I will bind the this value to my object so the value will be pulled from my object not from the global variable so let's say that here let me actually comment this one out save it and let's run it ok hopefully that makes sense there's another similar function called apply and they're very similar and in this context won't be obvious how they're different because I don't have any additional properties to send in or rather input variables to the third function so if I had something like a name I would use then like call. You know Bob but this can also take an array here in the apply which could include Bob so see what we get I haven't tried this beforehand so yeah object Bob ok now just out of curiosity what would happen if we did this probably nothing at all just be blank yeah object undefined alright global object with the word undefined next to it ok so hopefully that makes sense what I just added on there that's really to illustrate the difference between call and apply and so if I had multiple input parameters in the call I would just add them on there if I had multiples I could add them on inside of an array alright that's the only difference ok but let me just kind of annotate this and talk through it just for a moment so just to kind of recap this the this keyword depends on how a function is called and an object can be passed as the first argument to call or apply and the this keyword will be bound to it like we did here in lines number 54 and 55 alright and so just to kind of remind you about this I'm going to go ahead and say this property is set on the global object and then and it works inside of here this will return something different depending on how we call this method right and then just want to add this little annotation here as well both call and apply allow you to explicitly set what you want to represent this or how we want to bind this the difference is how the additional arguments are passed in like I show you here ok so when it comes to calling a method of an object the call site will be the object itself and all of its properties are available to this in fact if we take a look back here that's what happened that's how I did this and why I use this dot make and this dot model again when it comes to calling a method of an object in this case print description the call site in this case car dot print description will be the object itself and all of its properties like make model and year are available to this inner function only when I use the this keyword because this represents this context because I'm calling print description using the car object alright so to call the function I would use the object reference that object reference car gets and to this keyword so to further illustrate this idea let's do this I'm going to actually select everything we've done from here down and shift alt and a and so let's go function fifth and here I'm going to go console dot log and this dot first name and a space and this dot last name and hopefully this will make a lot more sense alright so now what I want to do is create two objects so let customer one equals and we'll go first name colon last name colon taber and then I'm going to create a print property that's going to point to the fifth function like so and I'm going to copy this and just duplicate it I'll make this customer two called richer bouton alright and then finally we'll go customer two dot print customer one dot print alright so now look at how this works what is context how do I call the print method that's pointed to fifth well in this first case I'm using the object object customer two that is the context we're going to bind this keyword to customer two because I'm calling it as a property of customer two I'm going to bind next in line number 85 the this keyword of the print method to customer one so let's go ahead and so to me this example is really interesting because the call site is the objects reference to the function and the this keyword can be used to reference the various properties of the object that was used to call the function so it becomes an interesting and elegant way to essentially pass values into a function without defining a bunch of input parameters to the function itself so now what I want to do is kind of stop working with node for a little bit and look at the this keyword in the context of a web page so I've created a new this keyword dot html I can use the term dock you can see that when I type in the word dock it's in an Emmett abbreviation if you're not familiar with Emmett just search for it online it's basically a shorthand syntax for I guess you could say for snippets for code editors right so when I hit enter on the keyboard it kind of creates this bam this whole document outline for me and it has some replaceable areas like the device width and the initial scale and the content and all that business I don't want to change any of that stuff what I do want to do is add a script section near the bottom for reasons I'll talk about in another video and then what I want to do is above that create just a simple button so here we go button and inside the button I'm going to say hey click me and then I'm going to set a on click equal and we'll come back to that in just a moment here I'm going to actually create a function that I want to call whenever the button is clicked so function and I'm going to name click handler like so and inside of here I'm going to go first of all I'm going to allow something to be passed in I'm going to allow a value to be passed in and then I'm going to print out whatever that is to the console so console.log arg now we'll come back to this in just a moment I'm going to leave a space and go console.log this and then in here I'm going to say the button on click equals click handler so I'm going to call the click handler I'm going to pass in this the this keyword so if all goes well here I should just be able to right click on this and say reveal an explorer and then when it's in the windows explorer I can just like hit the enter key on the keyboard to actually open it up in my default browser and what I want to do is I want to use the f12 tools in in edge I'll bring up this little window at the bottom here and I want to look at logs so make sure that you're on the console tab and select the logs sub tab and click the click me button and we'll see the results of both of our console.log in the first case what we get back is the this that was passed in as arg it out directly to screen and so in this case the this keyword will reference this entire element so let's take a look at that again here you can see how button on click gives me the whole thing so I can do something like this which if you're familiar with web development should not blow you away I should be able to do arg dot enter text and if you're familiar with web development at all you would expect to see what there let's refresh the page click click me button again you see click me that's the enter text of that button so I'm able to get to all the properties of this button but the key here is that the this keyword represents this entire button and I'm passing the this keyword in so that I can look at this entire button grab a property out but when I use the this keyword inside of my click handler function what do I get I get the global object now we said in node the global object the name of it is global in a web browser the global objects name is window so I can actually just like use this little arrow this little carrot chevron right next to object window and it will allow me to view all of the objects the child objects of the window and there are literally maybe if not hundreds definitely dozens of different objects and properties that we can that we can inspect and change programmatically we'll come back to some of those ideas a little bit later but basically the takeaway from this is that whenever code is called from an online on event like on click on event handler it's this is set to the DOM element on which that listener is defined that's why we got back this entire button including the text including the closing button tag but we've not taken any special steps to bind this inside of this function we've defined the click handler so it defaults to the global object the window object ok so the moral of the story is that what the this keyword is bound to is not always obvious it takes a bit of detective work more so than this keyword in other programming languages but it has to do with how a given function is called and the site from which it is called in this case this keyword is used at the call site is at this element level in this case the this keyword is used at the global level alright and that will change the value of this and what it's bound to but by default functions that are called using the method invocation operators will use the context in which the call is made so if the call is made in the global context then this keyword will be bound to the global object if the call is made in an object then like we saw here near the end the this keyword will be bound to that particular object and we were able to use it to grab out the values of the given object and you can take control of what the this keyword is bound to by calling it using either a call or the apply method of a given function and we talked about what they do and how they're different and finally whenever you use them in a browser once again what this is bound to depends on how it's being called and who is calling it so hopefully that clears up what the this keyword is I've given you a lot of examples I've tried to speak a little bit more slowly and hopefully you can wrap your mind around what this actually is and hopefully from this point on you'll be able to identify what this is in your code hopefully that helps you're doing great, hang in there we're getting close to being more than halfway done and you're doing awesome thanks in this lesson I'll briefly demonstrate how to use destructuring which is a fairly new technique in JavaScript for unpacking values from arrays into individual variables or I guess into other array elements of a different array but you can also use it to unpack properties from objects again into other distinct variables or a different object so use this term unpack you'll see what I mean here in just a moment let's start by creating a new file called destructuring.js alright and the first thing to do is create a bunch of loose variables here just a, b, c, d, e we'll wind up using most of these at some point and then I'm going to borrow that array that we created a while back maybe recognize some of these names and then next up let's start by just destructuring this names array into a set of variables so I'm going to start off by using names which I know is an array and I'm going to use this bracket syntax and say take the first element of the names array and stick it in a whoops whoops whoops there we go and a take the next element stick it in b c, d and I could even change the order instead of d and e I'll go e and then d alright and so let's just do console.log a console.log b and then console.log d because that's a little bit more interesting now let's go ahead and print out c as well why not and then we'll go e alright and so here we'll go node destructuring alright so take a look at what happened we have this array we destructured it down into a set of individual variables and we start off with a representing the first element of the original array eddy the second element of the original array alex because we're grabbing them off in sequence I did something a little bit interesting here and so much that I switched e and d so that e will represent Michael and d will represent Sammy when I print them out going back to alphabetical order d then e Sammy's first then Michael alright so but the key to this example is that I've taken everything inside of an array and using this style syntax I've destructured it down to individual variables alright that's just one example there's some other interesting ways to work with this let's let's just go here I'm going to take all this I'll shift a comment it out and the next example I'll do a let others so I'm adding an additional variable here in addition to the other ones that we created originally and here I'll go um a b and I'm going to use this weird syntax of dot dot dot others alright equal names so now um console dot log a console log b and then let's see what gets put out into others alright so this time a david b is eddy just like before but this time I said basically everything else just go ahead and stick them in a new array called others alright so that's what we see here printed out from line 21 we get this array representation in our console dot log including Alex Michael and Sammy together alright so that's just another twist we can basically take some elements one by one we can then also kind of combine together entire groups of elements together uh let's move on to another interesting twist on destructuring so in this third case what I want to do is actually work with an object and so whenever you're working with objects and you're destructuring out of one object into variables or even into another object it's really like a form of projection if you're coming from other programming languages grabbing out the parts that I want of the original object and putting them into a new object with a different shape alright without having to take all the contents of the original object so I may only want one or two properties where the original has 10 or 20 properties so let's start off with just saying let year and model then I'm going to um start off with car equals but I'll get rid of that here pretty soon we'll start with let car equal but it won't matter because we're going to remove that and I'm just going to create a typical old object um like say w model be a y year will be 10 the value will be uh $5,000 alright and in order to destructure this what I'm going to do is actually remove this and say hey I want to take the year and the model and put that into a new object of its own then what I'm going to do is wrap this whole thing in a set of parentheses and then an end of line character like so so now we'll do console.log here that'll be the value here that I'm pulling out model will be that value there that I'm pulling from the original object and printing it out so let's see what we get alright so 2010 from line 34 and the 745 li from line number 35 alright so that's just some examples of destructuring um pretty simple concept it really is just a compact syntax that helps to clean up code whenever you're trying to map from one data structure into another or into a set of variables and that's all that it is alright so hopefully that made sense we'll see in the next video thanks another new feature of JavaScript allows you to create better literal strings through the use of templates so the term template literal is a kind of oxymoron parts of the string will be literal and parts will be templatized they'll be variable based on an expression and so you can inject in other values variables or you can actually run entire expressions and we'll see the use of a ternary operator in just a moment let's start off pretty simple begin by creating a new file called this template literal literals.js inside of here do something really simple let name equal bob alright that's not the template literal this will be console.log and now I want to use the back tick characters usually over the tilde if you're not familiar with that region of your keyboard it's usually right next to the number one two three one right next to the number one you'll have to hold down the shift key to get to it so there's one back tick whoops I'm sorry you don't need to shift back tick key alright usually above the tab key on your keyboard and so inside of there I'm going to use high and then whenever I want to add something variable that will get kind of injected in from the outside it will be interpolated from outside of this I'm going to use the curly braces and right before the curly brace I'm going to use the dollar sign character you can see that the syntax highlighting in visual studio code changes the color of this to this bright blue color that's cool and so then I can just say hey I want to use the name variable inside of there like so okay so we should be able to do something like node template literals like so and I get high Bob awesome so the other cool thing about template literals is that they will allow you to create multi line strings now before this you would have to do a lot of using the append operator and so on but in this case you can do something like and I'm just going to copy and paste this because I don't want to type all this out you can see here that I start my template literal with a back tick and I end it with a back tick down here at the bottom so I'm setting this sentence or sentences actually this paragraph equal to this whole string and I've split it up on multiple lines and there's no append character or anything like that what I can do is console.log sentence and the neat thing too at least from what I'm concerned is that it preserves the indentation level and the line feed character so you know I could do something a little more I guess artistic here come on let's do this just with spaces like that like that and it preserves that indentation level that I have pretty neat right alright and then the other cool thing is that you can do anything inside of the expression interpolation area that you can do in a normal expression so and let me comment all this stuff out control I'm sorry Alt Shift A and here I'm going to create a function real super simple function get reason count just a very pithy silly idea here and I'm going to hard code this to return the value one alright and I'll change it a little bit later so you can see the difference here but I'm going to create a variable called interpolation interpolation equals I'll use the back to character give me dollar sign curly braces we'll come back to those in a minute to try this alright here make some space for myself I can create any expression I'm going to use the ternary operator and so I'm going to say hey if get reason count just because I wanted to make things a little bit more interesting so I'm actually calling a function if it is equal to one and here's where the ternary operator comes in I'll say one good reason otherwise two reasons this is starting to pop over out of the viewable area but hopefully you can kind of keep track of using this syntax coloring you can see where the expression interpolation begins and ends inside of that here I'm going to evaluate the call to get reason count and if it's equal to one I'm going to inject that part of the string in here otherwise I'll inject this part of the string inside of my template literal and now I guess the only thing left to do is just a console.log interpolation like so let's go ahead and actually run this so give me one good reason to try this well maybe we should try two give me a few reasons to try this and I see the need for this all the time especially in web development where you may have one item in your shopping cart or two items in your shopping cart to change up the string that gets outputted to for the end user based on a quantity and probably other good uses of that as well so string template literals are a nice addition to the JavaScript language here again they can make your code more compact and readable allowing you to do some interesting things in line that would require a lot of appending of strings previously so doing great let's continue on and see you in the next video thanks regular expressions allow you to create a pattern to determine if a given string matches that pattern that you created regular expressions are there often just referred to as regex or regex are not exclusive to the JavaScript they've been around forever they can be used in just about every programming language and I absolutely hate talking about them because they make my head hurt I've not committed the syntax of regular expressions to memory and so pretty much creating a pattern to find something is hard for me and I've developed a few little crutches through the years so that I can approximate or fake my way through the usage of regex and I suspect you'll probably find yourself doing that as well unless you're one of those really annoying people that just commit to learning regex inside and out and then can impress people at parties based on that knowledge so I try everything I can do to avoid memorizing it or learning the syntax usually if it's something simple like making sure that a string matches the pattern of a phone number a zip code something that's fairly common especially with data in the United States I can usually find a good example of what I'm looking for online using a search engine or stack overflow but if it's something custom for the given project I'm working on then I have to go and relearn just enough regex to get through that project and then I try to purge it from my memory again so I'm going to show you where to go how to find the answers and cobble together your own little regular expression but I'm not going to pretend like you should go out and memorize any of this I know people have done it but I usually wind up hating those people because they're smug know-it-alls but I digress let's just take a super simple regex example and use it in JavaScript so I'm going to start by creating a new JavaScript file called regex.js and here we're going to say I'm going to create a simple variable called pattern and you can create a regex pattern by beginning and ending with a forward slash so in this case I'm just going to say hey search for this pattern where there are the exactly these three characters X, Y and Z super super simple pattern you'd almost never use something this simple unless you were looking for specifically the letters X, Y and Z inside of some long string that you want to search through or a series of strings alright but there's my pattern and so before we get started in earnest let's just say hey what are you really first of all I want to print it out and then I want to console.log working with a new data type or is this just a data type that we already know so let's go node regex and it looks like just attempting to print it out will just be a string representation of the pattern the type of the pattern is object so it's a special built in object to javascript we'll talk about some of those global objects this is just a shortcut to creating an instance of that global object for regex patterns okay so here let's continue on now and actually create some text that may or may not contain that pattern that we've defined so let value equal and this is X, Y, Z a test alright and so what we can do is there's a couple of methods built into both strings and regular expressions that allow us to use regular expressions against a string or use our pattern against this value in this case this variable called value so we'll start with console.log and we'll use our pattern. and IntelliSense shows us there's actually quite a few interesting things that we could use I'm going to keep this example simple and just say use the test method and so IntelliSense tells us that this will return a boolean value that indicates whether or not the pattern exists in a search string so what I'm going to pass in is the string I want to search through so in this case value and I would expect to get back a boolean a true or false if we can find X, Y, Z in that string so let's save it I'm going to comment out these guys now I'm going to save it and I'm going to get back here and go node rejects and it is true we do find X, Y, Z our pattern inside of the string so I'm going to comment that out the next thing that I might want to do is actually replace that pattern we found in that string with some other string that's pretty useful and I do that sort of thing a lot in software development this time I'm going to start with the string itself say value.replace and so that strings replace method has the ability for me to give it a pattern and then I also want to give it the value I want to replace if I find that pattern replace it with this string and I'll just use the word just like so this is just a test so I've removed X, Y, Z and I replaced it with the word just by using the replace method of the string passing in the pattern and the word there are a couple of other things those are the two that I find myself using most often here we can do something a little more interesting I guess log value.match and this match function will return back an object that it gives some information about what the string was what the pattern was if it was found what the indexes in the string like if you were to split it up into individual characters at what point in the string would we find the instance of that pattern match so here we're going to pass in the pattern itself so I'll save that and you can see it gives me back this array with the pattern we're searching for the index where we can find it so I think 0 is T so 0, 1, 2, 3, 4, 5, 6, 7 and 8 so the X pattern is found at the 9th character index 8 I guess it would be 7th character it's the 9th character index 8 so at any rate and then the original input was the entire string itself so we can actually modify this or actually grab that object out and work with it individually so match and pattern now that I have that array that we saw down here I can grab an individual part of it so console.log and here I might go match.index so just shows you how to get an individual part of it so here I can grab the index itself and I could use that to do some sort of custom basement logic if I wanted to do that I'm not sure I would ever want to do that now this comes to the part where I teach you how to cheat and if you really want to cheat you go out to your favorite search engine and you type in something like zip code or regex and then if you're lucky Bing will pop it up to the top whether it be from stack overflow or just gives you a nice little usage example right there in line that's a little dangerous because you don't know if this particular example was voted up or down you might want to go and actually search through the comments and see the one that gets the most upvotes and the selected answer and the one that doesn't cause any argument in the community the other way is to go and kind of trudge through this yourself by looking at this page and there's plenty of references out there I prefer the developer dot mozilla dot org website personally I think their documentation is awesome and here you can learn about the various special characters and regular expressions and try to cobble together your own regular expression to find what you're looking for but that's all you're going to get out of me that's all I can tell you about regex because I'm not a big fan of it but anyway just to recap what we talked about in this video you can create a regular expression literal with forward slashes you can use the regex's test method passing in a string to see if that pattern exists in that string you can use the match method to find more details about the match you can use the replace method of the string to replace a given match with some other string like we did when we replaced xyz with the word just and then like I just showed you here at the end I showed you how to cheat you already know this look online whenever you need regex whenever you need regex help ok so let's continue on we'll see in the next video thanks up to now we've looked at a number of types can you remember them off the top of your head we looked at string number boolean object undefined and function as its own type and there are a couple of others that we haven't talked about yet we'll talk about null later and then there's symbol which is new in the latest version of JavaScript probably won't talk about that in this course but what I wanted to point out though when we were using string in particular but this is true of the other of some of the other types that we worked with it seems to have some methods that are available to it to do some interesting things so for example whenever we looked at regular expressions and let me just create a new file here called natives.js whenever we looked at the regular expression lesson we did something like value which is a string set to this literal string this is x, y, z a test and we did value dot replace well how is it that this value has this dot replace method we really never addressed that how is it something like a string can have a method after all we said that methods are really just functions that are defined inside of an object so that would make a string an object right or no but a string is a string how can that be well actually both of those are true statements the fact is that the types we've been looking at so far like especially string and boolean and number are known as primitive types these primitive types that have corresponding built-ins or natives that are functions that return objects with a bunch of cool methods that are added to them by javascript so behind the scenes javascript does something interesting it the javascript compiler will coerce your primitive in this case primitive string into an object that's returned from a native string function with all kinds of cool stringy type functionality included so actually although we haven't demonstrated this yet you could create a string using the actual string function to do something like this and let me comment this stuff out here and so notice what we did here let string equal new then here's our function that built-in function string notice that has a capital S we'll talk about that in a moment alright and then we were to save this and then let's go ahead and get down here and type in node natives it works well kind of works almost exactly like a normal string we'll get to that in just a moment so before I address that specifically I'm going to work with strings in this particular video and with the string capital S string function the built-in the native string but what I'm about to say about strings is true whether we're talking about numbers or bullions or other other primitives that have an equivalent native associated with it alright so I want you to notice a couple of things and we'll work through this first of all this starts out just like any other variable that we're assigning to a string except we use this new keyword and I'm going to explain what the new keyword means in the very next lesson when we talk about constructors but basically this is what creates a constructor call to this function and then here we are calling a string function capital or uppercase S in string but isn't that bad form didn't you say Bob that we should create our methods with camel casing and so string should start with a lowercase S actually this is a special situation it's still a convention indicating that this is a function that should be called using a constructor call again more about that in the very next lesson so you'll get a part two to this but just keep that in the back of your mind we'll come back to it alright so whatever we run this as you can see here when we ran no natives we didn't get an actual literal string output instead we got basically an object that has a string property and a value set to howdy we actually need to call a method on this native that's returned from the string function to convert it into a primitive string for the proper display inside of a console.log so we'll need to do something like let me just comment this out and we'll go to string like so and now there we go we grab we convert that native that object return from our native string function back into a primitive string and then display it on screen ok so and while we're looking at things here just out of curiosity let's go console.log and then go type of my string what would you expect to see here well it is a type of object alright so again what's going on here is that these built in native types provide extra functionality like this two string method like this replace method and others that we'll look at in other lessons and they provide this extra functionality to their corresponding primitive types and so just real quick here's a list of those built-ins those natives alright so it includes kind of corresponding to the primitive string lower case essence string number boolean there's also an object a function and a symbol and there are built-in natives that do not have primitive versions the primitive version as you know of array is object and the same with regular expressions here regex but it does provide this native built-in with extra functionality for our arrays so the same kind of thing happens it's just not with directly back to a primitive it's to an object but it still works with any time we're working with arrays and then there are some other built-in natives that provide foundational data types I guess you can say for important features but are essentially just objects whose methods implement a lot of logic for their features so things like the date function and the error function will look at these a little bit later but in this lesson I want to focus solely on the relationship between primitives and built-ins so whenever we do something like this and let me just copy and paste some more code in here so here we're creating a literal string and then on this literal string I'm going to call this method to lower case behind the scenes what's happening is that JavaScript compiler is coercing it's wrapping it's boxing that primitive string my primitive into a built-in native equivalent in order to provide that rich set of methods that transform the string in this case to all lower case letters instead of all uppercase so if JavaScript is coercing wrapping boxing our primitive into this built-in native equivalent then what happens whenever we need to get a value back out of it well the JavaScript compiler will do the opposite it will unbox that object back into a primitive without you having to do anything special it manages it all on its own so in this case let's just kind of see what happens here just out of curiosity let's get the type of here we'll put the type of there alright and we'll see that when we run this let me make sure there's nothing else here let me comment all this stuff out too at the very top of that file alright so now let me save that and we can see that it treats this literal string as a string here in line 31 then in line 32 it does that unboxing thing that we talked about to take string make it into an object so that we can call the to lower case method on it and then what do we get back well at the point when we attempt to find out what the type of my primitive is it already has for our purposes essentially unboxed it back into just a primitive string so it's recommended that you stick with using the primitive and you allow JavaScript to do its magic the compilers can do this sort of thing without breaking a sweat so don't worry about all this boxing and unboxing it's impact on performance but but let's suppose that just for the sake of argument that you wanted to start out with a built in native and you want to explicitly convert that built in native version of a string into a primitive string how would you go about doing that well let's take a quick example and let's go ahead and move away from strings just to numbers but the same idea will apply no matter what I'm going to comment all that out let's go let my number equals new number notice capital N or uppercase N in number and then in the constructor argument we'll pass in the actual value that we want to set that number to so at this point let's do a console log and let's find out what the type of number my number is any guesses on what it will be let's go ahead and stop right there and let's make sure we understand it's a type object at this point now I want to take it out of that built in native and I want to grab just the value of my number out and put it into a primitive so here we go let my primitive I'll just reuse that variable name here equals my number dot and then to grab the value out regardless of whether we're working with string number boolean whatever the case might be we'll use this method on this object called value of so the value of method and now we should do a console log my primitive actually we know what the value will be what's more interesting is the type of so now let's run that and so here in line number 36 we're going to get it's an object but we use value of to retrieve the actual value of our built in native object into a regular number and we print that out in line number 38 so to recap the point of this lesson is to explain what these functions are that have the same name as our primitive types but with an uppercase letter they are built in native functions that are intended to be constructor called we'll learn about that in the next lesson and the JavaScript compiler uses these functions to return an object that supports lots of rich features to each primitive data type and we'll see those in upcoming lessons but the JavaScript compiler will box and unbox your primitive types into these built in native equivalents as needed and we'll do so without any help from you and we'll do it all behind the scenes and you can explicitly create instances of these objects and then use the value of method like we saw here just a moment ago to convert them into their primitive equivalents but it's not really necessary so what's this new keyword all about and what's this uppercase letter in this function name all about well I'm going to explain that in the very next lesson we'll see there, thanks so previously we saw how to create an object literal using this style of syntax and you'll note that I've already created a file called constructors.js go ahead and take a moment to create that yourself if you want to follow along I'm just going to paste in the card that the literal car that we created in a previous lesson here with the make model and the year property set to BMW 745 Li and 2010 respectively now there's actually another technique for creating an object and that's through the use of what are called constructor functions so let me go ahead now comment this out and then let me go and create a new function and I'm going to name a car and it'll have some input parameters one for each of the properties that I want to initialize upon the creation of the object that gets returned from this function so make model and year and then we're simply going to say hey the object that gets returned set its make property to the make input parameter that was passed in as the first input parameter and you're going to add a model property to that object and you're going to set it equal to the model parameter that was passed in and then you probably guess what this next line of code will do same thing with year right and most importantly whenever you're creating an object using this this function it requires the new keyword so let my car equals a new car with a capital C did you notice that I named my function with a capital C car I'll explain that in just a moment and IntelliSense tells me that it requires three input parameters into this function so here we'll go BMW 745 Li 2010 alright and so what's really going on here and let's just go ahead console.log just to prove there's nothing up my sleeve here my car and here we're going to go node constructors and there you go we get a car object that has the properties make model in year populated alright so what's going on here is that the new keyword creates an empty object calling the function in this case car it will take that empty object as the this remember our discussion about how the this keyword gets bound to the context from which it's called well in that case that new object kind of becomes the context for this function call and so this empty object starts receiving new properties on lines eight nine and ten with new values set to those new properties what gets returned from this whole thing with the call to this function is an object with properties make model in year already set alright so it's important to remember that the functions themselves that we define here beginning line seven are not constructors although if you're coming from another programming language like java c sharp you might be inclined to think in those terms because that's how they work but rather in javascript it's the new keyword in front of any normal function any function that makes it a constructor call alright it creates a a new empty object and it will pass it as the this to that function call that you make so the new keyword kind of elbows its way into the execution pardon me excuse me I need to get in here and it and it says to the function first before you execute I need to create an empty object and give that to you in the this so it's bound so this is bound to this new empty object and then it says okay now you can continue to do whatever you were going to do now the function itself could ignore that new empty object or could use it like we have in eight nine and ten here alright so just to kind of prove that let me go ahead and comment all that out and let's create a function my function and obviously something simple like hey I am a simple function right and then we're going to go var my function equals new my function and then we're going to go console log type of my function or actually let's go lowercase m or my function I've got some things wrong here like there we go that's what I want to do and so it's all kinds of problems with that line code but I caught them before I executed it so that's good alright so you can see here in line number twenty one we are creating a new empty object and then calling my function my function executes but not before a new empty object is kind of passed to it into this now this is not used in the body of my function so it's returned back to this variable of the same name but with the lowercase m probably should have chose a different name if that causes any confusion I apologize just remember lowercase m my function is different than uppercase m my function in this particular case but when we take a look at the type of my function it is object alright and so at this point you know it's an object so you can't really do anything interesting with it it's no longer a function so you can't do that in fact here let me just copy and paste this little note I put to myself in my notes here you can't really do anything with this particular object it's certainly not a function reference anymore it used the function as a constructor but the constructor function didn't really do anything to populate the properties of it and you know this will not actually do anything in fact if anything let's just see what happens if we run this yeah we get an exception here that my function is not a function so we really can't we can't do that alright hopefully that makes sense the right reasons why but the only thing you can do with you know what gets returned here my function is that you can attach properties and methods to that empty object which is kind of the point of the new keyword entirely alright so what about this uppercase first letter convention I said that it was a convention what's a convention what is this particular convention you know specifically well you're basically saying my intent is that this function be called using the new keyword that's what the convention is basically I am a function but I should be called I should be used as a constructor so you should only use a new keyword on me and I'm expecting an empty object be passed to me so I can set properties on it or maybe add some methods as the case might be alright so just keep in mind that in javascript what makes a constructor function has nothing to do with the function declaration itself but rather how the function is being called it must be called using the new keyword in order to be a constructor function so in the previous lesson we learned about the built in native constructor functions that return objects with properties and methods to wrap around the primitive types and give them essentially superpowers giving them new properties and methods that will operate on the primitive value new functionality like the two uppercase the two lowercase the length property and others that will learn about but that's why they're defined as uppercase s in string uppercase n in number uppercase b in boolean and so on that's why you can explicitly create one of those built in natives if you use the new keyword like we demonstrated in that previous video so hopefully that all makes sense if nothing else I hope you're learning how javascript is all about functions first of all and secondly how you call a function really changes the the meaning of the function and what it's intended to be used for it changes even in some cases the functionality that's defined inside of the function like in the case of this or perhaps changes the purpose of the function like we saw here with the new keyword and calling into the function alright so doing great let's continue on see the next video thanks javascript has objects and we've seen how to create a literal object and we've seen how we can construct an object using a constructor function in the new keyword like in the previous video in some of the most popular programming languages you create an object using a pattern called a class or construct called a class in other words you create a class named car and then you create individual instances of the car class as individual separate objects the further more you can create specialized versions of one class borrowing all the properties of that parent class in the new child class so you have an original class and you say I want to inherit everything that that original class does in my new class and then you can extend it by adding properties and methods to it to make it a more specialized version of that original or parent class so to kind of extend the analogy here I may have a car class but I want to create a sports car class that extends the definition of just a normal car and it adds on things that make it sporty same thing with a minivan it's just like a car it has some of the basic principles of a car but a minivan also has like number of passengers and cargo capacity things that make it unique a unique type of car alright and then I can create instances or objects based on that minivan or objects based on the sports car and those objects are both have similarities to a regular car but they have differences as well alright so that's kind of the notion of of classes and inheritance and classes and inheritance are a foundational concept associated with object oriented programming not sure if you've ever heard the term but it's a pretty big deal among software developers so you might be asking yourself first of all does javascript have classes well yes and no I mean in javascript you have objects and you can create an object and dynamically add properties and methods to it whenever you want to but objects are the focus in javascript in languages like C sharp and java and C plus plus you create a class and you add properties and methods to the class up front and they're static in so much that they cannot be changed so you can't be adding properties and method declarations to the object at runtime I mean you can but it's not the original intent of object oriented programming they can't be changed over the lifetime of any objects that are instances of that class so here in object oriented programming languages base languages like C sharp and java classes are the focus javascript objects are the focus C sharp java C plus plus classes are the focus the latest version of javascript does in fact have the concept of a class but it's a weird little stop gap measure to help people that are trying to make the mental leap from an old language that they might be familiar with like C sharp or java into the world of javascript to a dynamic object based programming model so I talk about javascript classes in one of the upcoming lessons and we'll get to that soon enough but I guess okay so javascript kind of supports classes kind of doesn't support classes what about inheritance well here again javascript yes it kind of supports inheritance but not really the kind of inheritance from traditional object oriented programming so in javascript you have something different called a prototype chain so let's suppose that you define a literal object like our typical car example that we've seen so many times won't even paste it to screen you know what it looks like it has a make model in your property right and so you define this literal object like our typical car example you like the properties and the methods that you've already added to that object and you would like to use that car object as the basis for a new car object you'll probably wind up changing some parts of the object's definition maybe some new values and a few of the properties you might even add some new properties and methods to that new object and I'm going to demonstrate a technique that allows you to construct a new object based on an existing object here in just a moment but when you do that when you create a new object based on an old object something special happens in javascript there is a permanent link that's created between those the new object always knows who it inherited all those properties its original set of properties from how did it get created it always knows the link between it and the prototype that came before it all right in other words the original object serves as a prototype for the new object and the new object is essentially chained to that prototype from that point on so in languages like C sharp and java and C plus plus those traditional object oriented programming languages you create a class hierarchy where one class inherits from another class so whenever you create an instance of the child class there's really nothing that's linking that instance of the child class back to the parent class so there's nothing linking that child object back to the parent class definition so here again the focus is not on the relationship of individual objects that happen to be linked to each other and kind of have a brotherhood but rather more of a parent-child relationship in traditional object oriented programming again the relationship between classes is the focus of object oriented programming whereas in javascript it's the relationship between between objects and how they're chained together it's a subtle but important distinction between javascript and traditional object oriented programming languages so some people use the term javascript prototypal inheritance but I try to stay away from the term inheritance when talking about javascript because it might conjure up traditional object oriented programming concepts that would mislead you whenever you're considering how it all works in javascript one of my favorite favorite javascript authors Kyle Simpson called this style of object based prototypal inheritance it calls it really linking to other objects or OOLU objects linking to other objects and I really like that description and by the way I'm not sure one way is necessarily better than the other they're different they're pros and cons depending on what you're trying to accomplish the given problem you're trying to solve so what I do want to do is have a better thorough understanding of how objects linking to other objects and what are some of the ramifications of that so that's what we'll do in the rest of this video so you can see that I have a new file called prototypes.js and here I'm going to paste in my original car this looks an awful lot like the car literal that we've been creating object literal that we've been creating up to this point now I told you that there's a way to create a new object based on an existing object and so let me do that we're going to say hey let our new car equal capital O object dot create and then original car alright so this point if we do for example console dot log new car dot make for example so let's um go node prototypes okay so we have this new car and what it looks like at least at first glance it appears as though we have a new object called new car and the value of the original car has been copied in of the make property of the original car has been copied into the make property of the new car but that's not exactly what's going on here as we'll talk about here in just a moment but at this point I have two objects I have the original car and I have the new car and I could do several things at this point with new car I could change the values of the existing properties that I have on new car I could add new properties to new car or new methods to the new car or I could delete the existing properties from new car but more interestingly I want to revisit something I said earlier about the relationship between the original car and the new car that there's a link between the new object and its prototype its predecessor the original car and so if we do something like console.log and we say object.get prototype of and inside of that method new car so tell me who the prototype of this object new car is and it'll say it's this object right here where the make is BMW the model 745 Li in the years 2010 so it's pointing to this original car so let's do this instead we can actually get a reference to my prototype prototype get prototype of passing in new car and then I can do console.log my prototype .make and so you can see here that I'm able to get back to that to the make property of the original car now there's no way to really prove that because they both seem to have the same values right now but we're going to push this a little bit further what happens if I were to add a property to the prototype in other words what happens if on original car I were to add a doors property like a doors count so if you remember all I need to do on an object to add a property is just go hey I just want a new property called doors so I do .doors and then I'm going to create the value and say hey it's 4 now let's go console.log new car .doors alright you can see that the new car gets this doors property and it seems to be copying that new property over but that's really not true but we definitely see that there's a link between the new object and its prototype the original car but how do I know if the property is defined on the new object or on the prototype well here's what we can do and so this is going to help us to kind of get to the bottom of this relationship right here we're going to start with the original car and says do you have your own property does this property belong to you or are you essentially borrowing it from your predecessor so first of all it's true that the original car has its own property called doors so console.log new car do you have your own property called doors and that's false so kind of tying this all together and kind of explain what's really going on here well whenever we attempt to get a property or call a method on an object JavaScript will go through a series of lookups to find the value or the definition of the property or the method in order to call it so after we created new car it had none of its own properties if we asked it for the value of one of its properties doing something like we did in line number nine it would find the prototype that new car links to and see that if it has its make property so we know that the new car does not have a property that we define on it called make but what about its prototype and yes the prototype the original car has a make property and it's set to BMW okay but once we do something like this new car dot make equals Audi alright so we are changing the property or actually we're creating a property on new car and we're setting its value to Audi at that point what happens is whenever we come down here and basically call the same essentially same line of code now in line 11 it's saying hey new car do you have a property called and new car says yes I do now I have my own property called make and it's set to the value Audi alright so no longer do you have to continue and look at my prototype to find the property and its value you can look at me and find the property and its value alright so JavaScript doesn't need to look at the prototype chain if the property is created and set on the new object that is essentially um created from the prototype so if we ask for a property that's not yet been defined so here we go let's go here in line number 12 console log new car dot whatever alright now think about this whatever property does not exist on new car whatever property does not exist on its prototype the original car so what happens next um well then JavaScript will traverse back and say hey original car what are you linked to and since we defined original car like this we're linked back to type object actually it is the um the built in native object function however the whatever property is not defined on that either so now what happens well finally JavaScript will do one final traversal asking the object built in native object what its prototype is and by default it will return the primitive undefined so when we get to line number 12 in fact let's go ahead and comment out just about everything else here I'm gonna hit a there and we'll get rid of all this just so we can kinda see what we're doing here so at this point what happens we get undefined why? because new car doesn't have a whatever property we look back and the prototype original car doesn't have a whatever property its prototype object doesn't have a whatever property and its prototype is undefined and that gets returned that's the end of the chain so to speak and that my friends is basically how the prototype chain works in JavaScript you don't have to use this you probably should know it although you could probably go your whole career and not really have to ever deal with it however this is fundamentally how all your objects work and why you get the undefined type returned when you attempt to access a property value that doesn't exist so I tried to make this as simple as possible but this is a post-beginner topic in fact I was looking at some tutorials online and I saw that this was actually an advanced topic but if you kinda understand what we're talking about here just think about how far you've come in your JavaScript understanding to get to this point where you can kind of understand what's going on that's impressive so I would just recommend that you watch this again you take a look at a few other tutorials online and you give it some time to sink in and you'll probably leapfrog over a bunch of people who are trying to learn JavaScript but not really pushing themselves past the absolute basics you're doing great hang in there we're making great progress and we're getting close to the end relatively close alright so we'll see in the next video thanks in the previous lesson I said that JavaScript doesn't have classes at least not in the traditional object-oriented programming sense nor did it have inheritance in the traditional object-oriented programming sense I explained how JavaScript is focused on objects and the linkage between objects that are based on objects we also looked at constructor functions that allow you to construct a new object from a function call but this really isn't a class in the traditional object-oriented sense either but technically JavaScript does actually now have classes or the notion of a class and it was introduced in the last version of JavaScript now JavaScript classes give you the impression that you're working with something that resembles traditional object-oriented programming but in reality nothing has really changed JavaScript remains object focused and objects can still be prototypally prototype chain together I don't know how to say it correctly JavaScript classes are what is termed syntactic sugar on top of the existing JavaScript object and prototype models that term syntactic sugar you'll see that frequently in software development circles it's programmer slang that means that they added a few keywords and structures in JavaScript but these merely map to existing features of JavaScript they don't really add new features per se so the syntactic sugar might help those who are transitioning for more traditional programming languages to JavaScript but JavaScript purists are quick to point out that this new feature the class feature in JavaScript may do more harm than good because at the end of the day you still have to make the switch from classic or traditional object-oriented programming to a more object-based prototype inheritance if you want to use that term and if you're working with prototypes you have to learn the things that we talked about in the previous lesson so in a nutshell let's talk about what a class is and define a class essentially a way to define and create objects just like there are function declarations and function expressions now there are class declarations and class expressions so let's start off with just looking at a class declaration and so you do something like class car whereas an expression would be more like let car equal class and then whatever ok so fairly simple and hopefully straightforward it's really declaration you give it a name and expression is well it's an expression so javascript classes can have a constructor function that gets called automatically whenever you use the new keyword so let's go with the declaration version of this I'll comment this out this expression so inside of the declaration let's create a constructor function you have to use the term constructor then you can add any input parameters that are essentially going to map to properties that you're going to add to a new instance of an object based on this class so here again you do something like make model and here and just like in the constructor functions that we learned about a couple of videos ago you still use this keyword make it will make this.model equals model this.year equals year ok so you can see similarities here right and then to create a new instance of an object based on this class you would do let my car equals new car passing in you know BMW 745 Li and the year 2010 ok so again I want to make the point here that that word or that name of your constructor function in a class definition in javascript has to be named constructor in order for this to work and here you're still using the new keyword new still creates an object instance it still passes it to the constructor function now in this case the name of the function is not car it's the name is constructor but you're passing input parameters into that constructor method and then using this context it's the new empty object that we're attaching properties to and then initializing their value to the arguments that are passed into the constructor hopefully that all makes sense and it's similar enough to what we've already learned that it kind of you can see where things are mapped again syntactic sugar on top of what already exists so you can also create methods on the class in fact let me do it outside of the constructor method so here I want to create a print method and you know I can do something like console dot log and then I'm going to go ahead and use our special since string syntax interpolation syntax let's make some space for myself here and I'll say this dot make this dot model and I'll format it a little bit with some parentheses but inside with this dot here so here again now that I have an instance of my car class called my car I can call print so and so let's go node classes and you can see I get the nicely formatted version of the information in my car class calling the print method all right now beyond these basics you can actually approximate inheritance at least inheritance in the classic object-oriented programming sense so in our case let's kind of go down here to the very bottom and I want to create class sports car and I have to use the key word extends car so right off the bat when I do that and I create a new instance of sports car let's do that so let my sports car equals new sports car now I don't have a I don't have a constructor function defined but when I use the open the open parentheses notice that IntelliSense still sees that I have make model in year why is that? because by extending sports car from car I still get the constructor method define on car and I can still set the make model in the year so here let's go dodge viper and I don't even know if there's a 2011 version of it but I don't know if they stopped making it or if they're still making it I'm not even really sure but it doesn't matter all right so at this point and we can even call mysportscar.print all right and now we get that print out here like so so we're extending we're borrowing the entire definition of our class and we are getting the constructor method define in car we're getting the print method define in car but I can extend and push beyond the boundaries of the cars definition by adding properties and methods so for example here let's just add a quick method and I'm going to call it since it's a sports car we're going to create a method called revengine which will be a unique print out of information so console.log and we'll do something that room goes the this dot model okay so now I can call mysportscar dot revengine and I get room goes the viper I guess I should have had a space right there all right now what if I were to do this I still have my car can I go my car revengine let's see nope can't why because it says revengine is not a function well it is a function it's just not defined on the car class it's defined on the car class's inherited child called sports car right so you can't access revengine from the car class and you know what honestly there's more to it than that there's some advanced scenarios but that should be enough to show you what class the class keyword and the extends keyword can do and how it operates and you can see the rough equivalence between what we did here and what we've done previously and hopefully you can kind of see that there is a mapping in that ultimately what's going on behind the scenes though is that we're creating a sports car object and it's prototype is car and we're adding on a revengine method but when we look up the constructor function when we look up the print method it's still using prototypes behind the prototype chain behind the scene to manage all this just javascript is kind of covering that up just a little bit with some different syntax okay so my personal opinion is that if you're coming from a traditional object-oriented programming environment and you need to become productive very quickly because you have a looming deadline or whatever the case might be you might be better off trying something like typescript which was created by Microsoft it gives you the feel of C sharp and java more so than javascript will and it gives you more of that traditional object-oriented programming look and feel and ultimately it will transpile down to pure javascript kind of out of the context of this conversation just what you should do is go to typescriptlang.org and you can study up on it a little bit but it's essentially a super type of javascript meaning anything you do in javascript will work in typescript but typescript gives you some extra features that will make it feel more like java or c sharp if that's something you need but most importantly if some of this doesn't make sense the things that we've talked about here don't be yourself up about it again this is a feature that was added for a specific demographic people coming from programming languages it may not have been intended for somebody who is just starting to learn javascript so don't feel like the pressure now to go out and learn traditional object-oriented programming before you can understand how to use class you don't even need to understand this it's just again something for a stop-gap measure for people coming from another programming language so it might not be immediately obvious to you in what situation you might find yourself using this and why you would prefer this over in previous lessons but at this point just focus on the language the fact that these things exist the fact that they were added for a reason and the reason is to help somebody else maybe not you specifically somebody coming from a different background to make that transition a javascript and ultimately I think with a lot of the things that we're talking about here their usefulness will reveal themselves to you later whenever you start programming and creating real applications with this language so you're doing great just hang in there we're making great progress the fact of the matter is that learning is iterative and if this is your first attempt at learning any programming language or your first attempt at learning javascript specifically no doubt you're going to need to come back to some of the ideas that we talk about in the coming days, weeks or months and you'll continue to come back to some of these ideas over and over I mean I keep studying and kind of pushing in new directions coming back to studying the basics and then pushing the different direction and you have to do that in order for these ideas to fully sink in over time I mean I've been working with javascript almost my entire career and I'm still learning things so it's just the nature of learning this sort of stuff there's so many details and there's only so much time in the day so don't beat yourself up you're doing great you're taking great strides towards understanding javascript so hang in there we're just kind of entering the home stretch now you've come so far just a little bit more and then you can honestly say that you've you've got a firm foundation of javascript to build on okay a little encouragement to get you over to hump here alright we'll see in the next video thanks in the most recent version of javascript you can define a function using a shorthand syntax called arrow functions and arrow functions since they are just a shorthand syntax for creating a real function and functions are used everywhere in javascript as you know by now you might not be surprised to hear that there are many different ways that arrow functions are used in javascript and there are many different syntax variations to boot so what I want to do is start simple and I want to look at a few practical applications of arrow functions but we'll start using them as frequently as possible from this point on and you'll begin to see them pop up just about everywhere so you can see that I have a file called arrowfunctions.js that I've already created and I want to create my very first super simple arrow function so here we go I'm going to create a function called high I'm going to set it equal to a set of empty parentheses what's called the fat arrow operator so equal sign in a greater than symbol after it to kind of resemble a fat arrow I guess as opposed to a thin arrow which has absolutely no meaning in javascript this fat arrow then we'll point to a body defined by an opening closing curly brace and then we'll do console.log howdy so far so good right one line of code an entire function declaration and we can just call high so here we go node arrow functions and we get a simple word howdy printed out that's easy enough so let's comment that out and move on to a slightly more interesting example we can actually go let high and inside of the opening closing parentheses we can accept an input parameter so what these really are instead of using the keyword function we just get rid of the keyword function but this remains and it allows us to define an input parameter name inside of after the fat arrow and inside of the body I can go console.log we use our special back tick character and we'll go howdy and then dollar sign closing curly brace name and a few semi-clones the ends of some things here really probably don't need this one per se now let's call high Bob howdy Bob okay so you can see that all we're really doing here is just creating again a shortened version of a function and we don't need the keyword function we just go ahead and start with the opening closing parentheses to define the area where we can add input parameters the fat arrow points to the body of this of this arrow function and inside of there we can just do whatever we want to do just like we can in any normal function even reference input parameters like we've done here now up to this point we've just been kind of creating what I call void functions they don't return anything but what if we need to use the return keyword let's create a different version of this so we're going to create add, add equals here we go we're going to allow this to take two input parameters A and B and we'll just do something super simple we'll hear once again but we will use the return keyword A plus B and now we can do console console.log add 7 3 and we get 10 printed to screen okay can you see this same basic structure here we're accepting two input parameters separated by a comma here we're still referencing those in that body that we've defined using open and closing curly braces use the return keyword it'll get returned to our method as a return value of our method call and here we're just passing in numbers getting that value back and printing it to screen okay so far pretty easy stuff right now you might be wondering how could I ever use this sort of thing what is its pertinence so I think that one of the ways that I see them being used the most is whenever you need to run a function over each element of an array and so let's use our let names equal and you'll recognize these names once again okay this time we're going to call the map method now this happens to be a method defined on the array built in native object that we learned about we'll talk about more of these helper methods built into the array built in native object in an upcoming lesson but the map is a pretty cool one because what it allows us to do is to basically iterate through each element of an array and when we it iterates through it will actually allow us to call a function and this is a perfect spot for creating right inside of here one of our arrow functions so in this case we'll say you're going to iterate through each element of names whoops I need to use the right word here names right and so here we're going to create an arrow function that accepts a name and what we'll do is kind of to marry these two ideas together console.log and then howdy name and you can see basically in one line of code I was able to map each element of the array to our arrow function it passes in the name to the arrow function in the body of the arrow function now we can simply operate on it just like we were doing previously but as a result now for every single element of our array we're getting a console.log with our little message pretty cool let's take this one step further continue to build on this idea let me grab this line again so I don't have to retype that and then I'm going to say let i equals 0 and actually let me just grab this line too because I want to do something a little bit more interesting because I want to show that you can actually do a little bit more in a single line like for example here I might increment the value of i and then use i here in the body but now I'm essentially doing you know two commands or two statements inside of the body and I'm not saying this will you'll do this very often but it's certainly possible so now let's do save that get back to that so now David 1 Howdy Eddie 2 Howdy Alex 3 Howdy Michael 4 let's continue to build on this and now let's use the return keyword kind of in the same doing the same sort of thing here in fact let's go var transformed equals names.map and then I'm going to borrow some of these pieces here again I'm just going to borrow that except I'm not going to call console.log I'm just going to return that string so we can get this all kind of lined up here so I'm going to take every name in names and I'm going to return Howdy plus the name and now I'll do console.log the entire array that is going to be returned from this and saved into transformed so here we go whoops I got a spell log right alright and so you can see that what gets returned here because we're returning multiple values and added to essentially an array and now you can see on each element of the array is the literal string that we construct inside of this map function using an arrow function to do the construction and those individual names are now transformed and saved into a new array instead of just David, Eddie, Alex, now it's Howdy, David, exclamation mark and so on alright so arrow functions are simple to create and they're just a shorthand version of function expressions they really are useful whenever you're working with functions on arrays like this map method that allows us to map each element of an array to one of our arrow functions and then basically execute that function against each element of the array and so we'll see some other examples of this in some upcoming lessons alright pretty cool stuff alright we'll continue on the next video we'll see there thanks designing a course can be challenging sometimes because when you finish a topic there's a number of directions you can go after that topic but if you have an overarching idea that you want to get to eventually you're going to have to kind of leave some important thoughts on the side and come back to them later and that's really what's going to happen in the next four or five lessons or so these are topics that could have easily been covered much earlier in the course but because I was trying to get somewhere I left those details off till now so hopefully you don't mind that we're going to circle back and fill in some of the or back fill some of the topics that we just didn't cover in a lot of depth and the first that I want to talk about are these terms truthy and falsy which seem to be specific to JavaScript I haven't seen them used in other programming languages maybe I just haven't looked at the right programming language but basically it has to do with evaluation so when you evaluate an expression like for example in an if statement or in a switch and you perform an evaluation of expressions sometimes they're going to return absolute true or false one is greater than two that is false patently false and I would expect that I would get from that expression the false value but then there are other things that are not quite as obvious and there are rules in JavaScript that dictate whether an expression is truthy it's in and of itself it doesn't look like it would be true but because of the rules of JavaScript it is true and things that are falsy doesn't look like it would be false but based on the rules of JavaScript we're going to call it false and so if you just don't know what those are you're going to maybe perform an or evaluate an expression you're going to get a true or a false and you're going to be like what in the world is going on there why is that true, why is that false so I want to cover these cases and I hope you don't mind that I'm just going to copy and paste these right in because it's a pretty big chunk of code and we'll just look at these things but in the top these are things that are falsy well right off the bat in line number one if you're going to evaluate an expression if false that's always going to be false that's not really falsy it's just false but then there are things like no if no well in and of itself if we're looking at this completely subjectively no is not true or false it doesn't really have a connotation of being true or false it's just no no later however it's considered by javascript to be a falsy value same with undefined undefined is not good or bad it's not true or false but javascript says that if something pops up and after evaluating an expression it comes to undefined that's going to be a false value the same with the number zero if an expression is evaluated and what's output is the number zero that is a falsy value it will return false in that expression same thing with not a number same thing with an empty string whether you use in lines six or seven single quotes or double quotes to define your string now everything else is pretty much truthy in fact I don't even know if there's the notion of truthy in javascript it's just everything is that's not in falsy is essentially truthy but I gave you some examples here obviously just like if false is falsy if true is going to be truthy it's just true but things like an empty object if you evaluate an expression and it returns an empty object for the purpose of of truthy and falsy it's truthy same thing with an empty array same thing with a string that's not empty so we saw empty strings are falsy but a string if you have something in it it's truthy okay an empty a new instance of an object is truthy even though there's nothing associated with there's no properties or methods doesn't matter truthy same thing with any non-zero value whether it be an integer or a float which means values after the decimal point those are all truthy as is a constant in javascript called infinity whether positive or negative infinity all truthy values so here again if you ever come across something in an evaluation it returns an odd value that doesn't strictly return true or false it returns null or undefined or not a number or zero or an empty string falsy it's going to the evaluation of that expression will be false but everything else is pretty much going to return true okay that's all I needed to say in this video hopefully that makes sense see you in the next video thanks continuing the sentiment from the previous lesson where we're kind of doing a round up of topics that by all rights could have been discussed earlier in this course but we're going to introduce them now I want to talk about the last of the data types that we'll encounter the data type null so it basically null represents a variable that points to nothing but an object reference was expected in that case so just as a quick reminder you can create a variable and not set any value to it not initialize the value not set the value and in both cases or whenever we look at the actual value or the type of the value it is going to return undefined so the value of a because we've not set it to any value is undefined and the type of a is undefined but here that's just a variable we didn't set it to a primitive string number or boolean or anything of the sort let's suppose that you actually are expecting the variable to hold a reference to an object so just to kind of copy a quick example from a previous lesson let me comment all this out and paste in this so here we have our regular expression example where we're going to try and match a pattern XYZ and we're going to use the strings match method passing in the regular expression literal that we created in line 5 but this time there is no match there is no string XYZ in my value variable so what is result set to well let's see what we get in this case we get result is set to null well what is the type of results type of result this is going to require a little bit of explanation okay that's the quirk with null it will actually return object not the primitive type null and that's a known bug in javascript that will likely never be fixed because too much code on the internet depends on the fact that type of null equals object is you know it's basically baked in and grandfathered at this point but by all rights if javascript had been designed correctly from the start that would be null but hopefully you get the idea there alright but the interesting thing about getting a null result when we expected an object back is that we can do something like this and I'll just copy and paste this instead of typing it all in we can check result and say are you you know and we'll do the strict equality evaluation is result null and if it is then we can say well no match was found xyz was not found in our value alright and so this can be extremely helpful whenever we're building our applications alright so just to kind of recap null the primitive data type null is not zero it's not undefined it's not an empty string it simply means that you have a variable where an object reference was expected but it's not set to any object reference it's different than undefined right because undefined says I'm expecting to have a value but one was never set and it was expecting maybe a number string or Boolean no no no we're expecting an object reference but we don't have an object reference at this time set to our variable okay so hopefully that makes sense and let's continue on see there thanks it's been quite a few lessons now since we talked about the built in native functions that return that return objects we saw at that time that there was a date constructor function and that date constructor function will return an object that allows us to work with dates and so I just wanted to take a brief look at what it can do and how you can actually work with date type information using the date object so let's start off with a very simple case here I'm going to say hey let today equals new date and that will by default give us right now this date and time alright so what I can actually do is actually initialize that date object with a specific date using one of several different formats so I may want to like create a date that represents my birthday so I'm going to create a new date and I'm going to pass in and this is interesting right because if I look at IntelliSense it has an up and down arrow I can actually use the arrows on my keyboard and it will show me the various versions of constructors that are available with which to initialize the state object so we can start off with something really simple and just kind of a full day like December 7 1969 and we'll give it a time even at 7 0 1 3 just guessing at the actual minute and second of my birth I don't really know exactly I know it was early in the morning that's all so that's one way to initialize the date but there's a couple of other ways and let's just do like let bob equals new date and there's a file system date type that looks something like 1969 dash 12 for the month dash 0 7 and then t for time and then 0 7 because it's on a 24 hour schedule colon 0 1 colon 23 and that's roughly about the same these two will create the same basic time alright there's also we could just kind of simplify things a little bit here using a different format just just give it the year month base 0 and day I think base 0 as well though I haven't really I'm not really entirely sure about that and then Bob equals new date it's kind of the same thing 11 6 and then 7 1 7 comma 1 comma 23 so I think these are about the same I may be off by one I forget if it's 0 base or 1 base but you can look that up fairly easily I'm not going to use these but I just want to show you that they exist okay but we have here now today's date and my original date my birth date and so what we can do is something interesting like get the time that's elapsed between those two dates by just saying bar elapsed time equals n equals today minus Bob console.log elapsed time and what will get back to me is the number of milliseconds alright between those two between those two dates so this is the number of milliseconds and I can divide it out calculate the years, the months the days, the hours, minutes and seconds if I wanted to alright so that's one thing that I can do is determine the elapsed milliseconds between two dates you can also get parts of a given date so I can go console.log bob.getDate and it returns 7 what does that represent? that represents the day of the week so in this case Monday would equal 1 and Sunday would equal 7 which seems a little backwards to me but hey that's what you get when you create a language and you set an all equal object to another kind of quirks like that moving on console.log bob.getTime and this will be represented the time of day in our date object so that was the number of milliseconds and so that's a little bit less useful but you can do other things and let me just paste in a bunch of these all in one shot you can get the month, the day hours, minutes, seconds and milliseconds and then there are also some additional date functions for things like conversion to UTC or universal timecode and local dates and times so converting back and forth between UTC and local date time and that's pretty much what you can do with the date object and so let's continue on in the next video. Thanks previously when learning about built-in natives I explained how the string primitive is mapped to the string built-in native object and by boxing the string primitive into its equivalent string native object, built-in string native object JavaScript therefore will supply us with a rich set of functions. Now in this lesson I want to demonstrate just a handful of these very useful string methods that are supplied to us by the string built-in native object and explain why they're useful and I'm just going to pick the ones that I think are useful at least they've been useful to me in the past because there's a bunch more and I would just recommend that you use Bing or your favorite search engine to search for JavaScript methods of string and you might find the Mozilla developer site and it will give you a full listing of all the methods that you can get on that string object. Alright so first of all we're going to need a few strings to work with just for fun and so I'm going to create some different ones here to our quotes so the first quote is knowledge is power but enthusiasm pulls the switch and second is a famous quote from a good friend of ours do or do not there is no try and then finally a listing of random numbers that mean absolutely nothing and then you know one of the things that I didn't really mention at the time is that you realize that and I'll just put this here you can even call these these methods on string literals like for example console.log bob loves you dot isn't that crazy that you can just do dot on a string literal and call to uppercase you certainly can so let's see this message in all of its glory because I do in fact whoa let's call strings I do in fact love you alright let's move on alright so let's let's use a couple of interesting interesting methods of string so we're going to use the split method I'm just going to call setMySplit equal to the third this third one define on line three with those variable with those values those numbers that are separated by commas and the split method will allow you to say hey every time you see a comma split that up and take the element in between the commas and add that to an element of a new array and so let's go console.log MySplit and here we have an array with each value as a separate member of or separate element of that array pretty cool so you'll do this a lot whenever you're working with data and it comes to you in some sort of something like format you can split it out alright next up we can slice a string so let's go letMySlice equal first.slice and then we give it the starting index and the ending index just to kind of pull out one little piece of the string and put it into its own variable so then we can do a console.log MySlice so this first sentence we would count you know to the position 13 and then to position 18 and hopefully we'll grab out that word and we do we grab our power same basic idea with the next one which is substring it's just a tiny bit different so let MySubster equals first.substring and here we'll start with that same index but we'll say just instead of giving you the end position just go over five positions so this is the start and then this is the length that we want to pull from that from that first string and so then we'll console.log MySubster and we get the same value there okay similar ideas between slice and substring moving on we want to return true or false if our string ends with a given string to compare it with so MyEndsWith equals we'll use that second string that I created here try or do or do not there is no try and we'll say hey does that string ends with true or false the word try period and then we'll go console .log MyEndsWith true right and hey well then we can do sort of the same thing let my startsWith equals second .startsWith and so this is just a way for me to say hey is this the string I was expecting does it have the values in it that I want so I can say does it end with this does it begin with this true or false alright so that's true as well and then we can even say hey is you know some place in the string does it include the substring or the string there so is the word there used in that second string console.log my include whoops there is no there alright how about capital T in there that's true alright so it is case sensitive alright so let's come in all these out interesting now let's say let my repeat equals ha exclamation mark space .repeat and the number of times I want that repeated is three and then let's do a console.log my repeat and I get ha ha ha so the repeat method well repeat whatever the string is the number of times you tell it to and then we save that off to do its own variable and I think the last one we're going to look at is a way to kind of clean up a string so let my trim equals bunch of spaces here and then in between I'm going to say this is bloated right and I want to clean it up a little bit so I'm going to go console.log and the first time through I'm just going to say trim.length this will give me the total number of characters in that string but then the second time I'm going to do what's called chaining method chaining so my trim. I'm going to use the trim method that should clean off all the empty spaces at the very beginning and the very end of my string and then I'm going to grab the length property so you can see .trim .length I'm able to since trim will return a string then I can call the next method or property on the string because I'm working again with the string type so I'm chaining those calls together to get the result essentially the before and after so before I call trim we're looking at 16 total characters here but when I call the trim and I get the length there's only 7 characters that means the word bloated should only be 7 characters long it is alright so those are some helpful string methods on the built in native string function constructor function and we'll do the same thing for array in the next video we'll see there thanks since we gave strings methods the proper treatment I want to do the same for arrays so we'll do that here and let me create a couple of arrays here I've got an array called names and an array called others got an array called lost and an array called Fibonacci so the obvious difference is that here I'm working with strings here I'm working with numbers so we're looking at methods that can be applied to arrays so the first thing we can do is combine two arrays together so we can use the concat method so here I'm going to take the lost numbers and I'm going to concat them to the Fibonacci numbers giving me a combined set of array values node array-methods the name of the file I created and I get a long set, a complete set where you can kind of see the division between the two sets now they're all in one array okay seems like it might be helpful at some point otherwise we'd have to loop through and push or pop I mean push elements of one array into the other array that might be a little bit a little bit of a cumbersome process you can also do something interesting like console.log and we can take combined or the combine we don't need that we can use Fibonacci and what we'll do is call join and I can say hey join all the elements of the array together and separate them with this string so I'm just going to use like a tilde here for no other reason than the fact that we just haven't used a tilde yet and I think now we've used every character on the keyboard at least once alright so let's save that and then run it and you can see that I just merely printed out the Fibonacci numbers with a tilde join them together into a single string but they're separated by a tilde now okay so what we're going to do about or demonstrated push and pop I don't want to go back into those but there are essentially ways to add elements to the array or remove the last element from the array there's some other ways to do that too for example here we've got a console.log we'll take the loss numbers and we'll call the shift method and what the shift method will do is we take one item off the front side of the array and it'll return it back to us to print out but then if we go and look at the array we'll see that it actually removed it so it's essentially a pop but instead of working off the back end it works on the front end okay so let's see that in action and we get that exact behavior that I described we can do something called an unshift which is to add items to the front so it's essentially just like a push except we're going to add items to the front one or more items so here we go with the lost unshift and then we're going to say hey let's add we can add one we can add two we can add a bunch of items and so now when we console.log loss numbers oops we'll see whoops what did I messed up I call it list instead of lost there we go and so now I've added the values 1, 2, 3 and 4 as new elements of my array and then it continues on with 8, 15, 16, 23 and 42 okay let's come in all these out moving on let's let's find an element first of all here console.log let's take the names and reverse their order so first of all we'll start with the original order and then we'll tell it to reverse and we'll print that out so originally David, Eddie, Alex, Michael but then we get Michael, Alex, Eddie, David furthermore what we can do is go console.log names.sort names.sort names.sort it's a sort method I gotta use the methodification operator so now when I run it we get the alphabetical order Alex, David, Eddie, Michael alright next up let's let's see how you can identify where a given element is in an array by looking up its value using an index of method so here we're gonna go console.log and we'll go others.index of and I'm gonna look up the element name mark alright and so let's see where it's at it should be the third element of the array so I'm gonna go back up here to others 0, 1, 2, 3 it's at the third element so then I can go grab it um how about we look at and find the last index of and let's take those combined numbers remember those all those numbers we basically put them together let's go the last index of the value 1 so here first of all let's do this just so we can easily see what the current value of combined is and then we'll say hey we're gonna search for the last time the value 1 appears in my list which array the element is it at whoops what did I do this time I think it's just combined right still not right because I commented it out now let's try it there we go alright so you can see that our combined variable holds 4, 8, 15, 16, 20, 3, 4, 1, 1, 2, 3 so now I want to see what element is the last and it says it's at the seventh element so 0, 1, 2, 3, 4, 5, 6, 7, 0 based so the last index of 1 would be at 7 so it's useful if I'm looking through a large set of data and I want to find the last instance of a given value I can use last index of instead of index of which will give me the first index okay alright moving on previously we looked at the map function of an array I don't want to belabor that because we've already seen it but we can do other interesting things too like we can create a filtered list so using arrow functions so var filter equals and we'll go with combine dot filter and now I'm going to give it an arrow function so for every number I'll just say it's x I can give it any input parameter name so here's the body of my little arrow function if x is less than or equal to 15 then I want to return x alright and effectively what will happen is it'll return only those numbers that match this expression so that when I do console.log filtered I should only see numbers that are less than or equal to 15 and so I get a filtered version of that combine array pretty cool and a good example of why you'd want to use arrow functions similarly you can do something using a what's called an iterable it's a method called for each so this will go through each element of an array and inside of that I can then create an arrow function similar to things we've done in the past where I'm actually just going to for each element of the array go ahead and console.log this string and interpolate in the name that's passed in pretty cool and then we can also do some checks so for example I can say hey can you tell me if every one of the values inside of my array match a certain condition so here I would go console.log and I'm going to take that filtered list that I just created here so this should contain all of the values that are less than 15 from my combine and here I'm just going to say hey let's go filtered is every one of those values and here's where I'm going to create an arrow function so let's call this num are every one of those numbers less than 10 sure false false why is that well I happen to know that there's at least a 15 in there maybe if we increase the number to something like 16 are all the numbers less than 16 will they better be because they wouldn't match this criteria right true okay so that's the every method of an array similarly we can look at some so tell me if at least one element of the array matches a condition so here again console.log start with that just create an arrow function so whoops start off with use the Fibonacci numbers so some true or false well let's start off here with an arrow function number are all the nums greater than 50 true or false are they all greater than 100 or are there any of them there's at least one item greater than 100 that's what we're testing for here false there's no items in that Fibonacci sequence that we have here in our array that are greater than 100 alright so hopefully first of all you can see that there are some very useful helper methods on the array built in native secondly more examples of arrow functions that are used inside of some of these methods hopefully that's useful let's keep going see in the next video thanks you have to try really hard to force JavaScript compiler to throw an exception with the code that you write unless you simply just typed in the code incorrectly now I suppose some might consider the fact that JavaScript tries so hard to work with whatever crazy code you offer it as a positive thing but personally I wish that JavaScript compiler would throw errors more often I mean you should never be able to do something as absurd as what I'm about to do here when we paste in a little code I mean this makes absolutely no sense here we're going to attempt to multiply 7 times undefined divided by Panama okay what's the answer to that well it looks at it and says well you know I'm not really sure that that's going to come out to be a number so I'm just going to return not a number and we can check for that not a number and you know I guess we can account for that in our logic of our application but kind of wish it would just throw an exception but I guess that's not the way that JavaScript is made to work I suppose it tries to do whatever it can because it I guess figures that perhaps people come from many different programming backgrounds or that since it's a dynamic language maybe it should be able to accommodate any of these crazy situations but when JavaScript does encounter finally something that it cannot work with we call that an error we call that sometimes an exception an exceptional situation an exception something it just can't work with and the JavaScript runtime will simply quit at that point throw up its hands and say I can't do anything with this line of code and if I can't do anything with this line of code that means I can't do anything with any other lines of code I quit so it's when it does actually reach an exception it completely bails out on any additional code that you might have written alright so when this happens and you can identify where in code these issues are likely occur you can and should build some safeguards to ensure that they never happen again like in this case we might write several lines of code prior to attempting line number one we might do things like to ensure that if for example these values were contained in variables we might try to make sure the variable was not undefined we would try to make sure that the variable had a data type of number and not string or something else right so that we could do that calculation and expect a real number to be assigned to the variable a if we were working with objects we might want to make sure that the property actually existed on the object that was passed into our function and so we would look and say do you have a property with this name does it have a value okay we can work with that and so there are some safeguards that you can kind of build around your code to bolster it to make it to make it more resilient to the possibility that its inputs were bad and that it ultimately might throw or raise an exception so other times these things might be completely out of your control you still need to write your code in a defensive manner so for example you might want to request data maybe jason data from a web server that hosts a web api and depending on what you're requesting and depending on whether the web server is functioning correctly in that moment you may or may not receive the data that you're expecting so this might cause your code to throw an exception well here's another case where you should be able to kind of code defensively account for the possibility that an exception could occur because calling into another resource across the world is a highly risky proposition and it could result in an exception in an error I use those terms kind of interchangeably in my mind they're the same thing but whenever a problem arises an exception is raised by javascript in some way the information about that exception is boxed into one of these built in natives that we learned about several videos ago that were created in the exception capital E exception function and it will give you an opportunity to inspect that exception or that error object and look at for example the error message and be able to handle it gracefully and we'll talk about that in this lesson you can safeguard your code the code that you suspect or that you know would be prone to throwing exceptions and you can do that by wrapping it in a construct script called try catch so here let me comment this out and then I'm going to create some examples let's create one where I know I can create an exception so here I'm going to create a function called before try catch so here we're just going to create one and not attempt to catch any issues that might be that might be created now here I'm going to just say let this variable obj equal to undefined and I'm going to act like obj is an object so I'm going to just act like it should have a property on it so I'm going to do console.log obj.b all right and I know that this obj does not have a property b that should trigger an exception in JavaScript it's one of the few cases where we can actually force it to happen so if that happens correctly as I suppose then you should never be able to execute this line so if the previous line of code throws an exception you'll never see this all right and just want to point this out here I'm going to have to escape this in my literal string this single quote in the contraction you'll because JavaScript and in this case Visual Studio Code doesn't recognize it as an apostrophe it recognizes it as the closing single quote for my literal string so to escape that character and treat it like I need to treat it as an apostrophe I'll use a backslash right in front of it so now that little combination of characters will treat it as an escaped apostrophe instead of the closing single quote all right but anyway just an aside there line seven should never get executed because I am expecting line number six to essentially throw an exception so here's what we'll do we'll just call before try catch and we'll execute that and you can see that cannot read property B of undefined perfect all right now let's introduce a different function called after try catch to kind of show you how this works I'm going to comment out the call to before try catch here let's just grab all this and copy it all but I'm going to first of all create a try and I'm going to go ahead and just hit enter on my keyboard I'm going to use the arrow keys to like create a try catch statement all right see that and inside of the try I'm going to attempt to perform these three lines of code now I don't have high hopes for 17 ever ever running however I suspect that what I can do is do something like this if we were to reach an exception in line number 16 which we will so in this case what I can do is say I caught an exception that was thrown by the JavaScript compiler and I can even inspect that error object and I know that it has a message property so we'll do something like that but the key here is that this will not break my application my application can continue to execute so I can go console.log my application is still running so even if we encounter an exception like I suspect we will in line number 16 we can catch the exception handle it do something and then move on so let's start with this then we can move on see there's other things we can do here whoops what am I doing wrong here oh I need to actually now call my after try catch so now let's try to run it alright I caught an exception cannot be property be of undefined but my application is still running so it did not completely just shut down my application perfect now what I can do is actually add another statement called finally and this will run regardless of whether my try makes it successfully all the way through or whether the catch has been invoked so I can just do console.log this will happen no matter what alright and usually use a finally statement to clean up any resources that you no longer need I'm not sure how useful that is in JavaScript personally but you might find a use for it alright and so you can see that we have hit the catch but then it also executed the finally statement before continuing on with the remainder of the application so there's a pretty effective software development strategy of throwing custom exceptions from your functions with the intent that those exceptions are caught by the caller so it's a form of communication if it succeeds then it should succeed quietly but if it fails your function would then throw an exception that would be handled by the caller and it can decide what to do next so I'm going to comment everything we've done so far out and we're going to create one more example here so let's do that and I'll comment all this out too and let's go here so this time let's go function reform calculation and this calculation will take and look at an object that will pass in and we're going to say hey if that object obj. has own property b wait if it doesn't have its own property so I could do equals false like that or I can do a shorthand version of this by just using the exclamation mark right before the expression see that that exclamation mark it kind of makes it the negative so if has own property returns false then the entire expression will be true this is if it not has own property equal true essentially then what we can do is actually throw a new error so here we'll just describe or give it the message we want to tell what the problem is object missing property alright otherwise if that turns out to be a truth that the object does have its own property then we can continue with the calculation and I might just return the value 6 or something like that whatever the calculation using obj. property b so here we go now we're going to call into that function perform higher level function operation and here let's do let obj let that value equals 0 and then let's do a try around value equals perform calculation and I'm passing in an object that's undefined right because I didn't set it to anything in line 41 so I know it's going to throw an exception here I'm going to catch it I know it's going to come back to me as a boxed built in native error and print that out and what I can do then is kind of to show how this would work is if you know value is equal to 0 I know that the perform calculation didn't work so I can run my contingency perhaps I can do some retry logic you know whatever I need to do to make my application handle this exception gracefully and then continue with whatever logic makes sense after that so let's see if this works I think I got this right let's call perform higher level operation and I'm not sure what to expect to see here but I don't want to see any exceptions pop up other than the one that I'm printing out and throwing here so alright I think in this case I'm going to need to do this let's see if that works alright try that again alright that worked perfectly okay so in this case created an object passed it in doesn't have property B so we throw an error remember this is a strategy for us to do some checking and then look to make sure that if an exception happens we can handle it if not we grab the value back but if the value is zero then perhaps we need to we hit an exception maybe there's some other flag we can use to see whether we're getting the value we thought perhaps in the catch we can do some work maybe in the finally statement it makes more sense to put it there but at any rate we can gracefully recover from the exception being thrown because that's kind of just our strategy that hey this function does not have what it needs so you're calling into it but you didn't give us what we needed so you're going to have to write some logic to figure out what to do next alright that's all I'm trying to say there so this is a good start to help you understand that you do have options when you think about how to safeguard your application against potential exceptions that could occur and shut down your code completely ideally you could think of all the ways that your code could possibly fail and attempt to mitigate those potential issues up front but after you've done a reasonable amount of work to perform gated checks like I demonstrated here in line number 33 34 and 35 then you can ultimately wrap your code in a try catch statement try catch finally whatever works for you and furthermore you can throw customers from one function to another as a means of communicating failure and allowing the caller to implement some contingency like we looked at in line number 50 there maybe even some retry logic to ensure that ultimately the application is performing correctly and it can recover from any exceptional situations alright that's all we really wanted to say alright so we're doing great almost done we'll see in the next video thanks up to now I have avoided talking about JavaScript in the specific context of a web browser I actually re-recorded this entire course from scratch earlier this month because I started talking about JavaScript in a web browser from like the very first video and it became obvious as I that I spent so much time fiddling with the HTML explaining the DOM and ultimately I was struggling to get just to talk about JavaScript by itself and so that's why I took a different tact and re-recorded this so this time around as you know I started with pure un adulterated JavaScript and now here at the very end of this course I'm talking about JavaScript and how it's used in a web browser which there are some peculiarities that I wanted to talk about and I hope the approach makes sense I hope that this approach work for you and even if this isn't how you wanted to learn JavaScript I hope you can understand and see the rationale behind it alright enough of the pretense as we start dipping our toe into JavaScript in the web browser I want to talk about the amazing work of a web browser and how it will actually turn a request by just typing in an address into the point where we're actually viewing a page on screen I want to talk about how it begins to understand the HTML that it has downloaded as well as other files like CSS and JavaScript files and I want to talk about all the things that it has to consider before ultimately rendering a web page out to the end user to see it's really quite amazing so let's start at the very beginning I want to talk about all the process of requesting and resolving to an IP address and all that let's just speak in very broad terms there's a request made from the web browser to a server and ultimately an HTML file will be downloaded or I should say a collection of HTML is downloaded to the web browser and then there are references to other resources like CSS files and JavaScript files and things that begin to be downloaded as well kind of all this happens really at the same time along with everything else I'm going to talk about here and this isn't really intended to be deeply technical I'm really just going to paraphrase the general order of events because I'm not really privy to what goes on inside of a web browser I haven't really looked at the source code but any rate while it's downloading all the resources it has its HTML now it's grabbing its CSS now it's grabbing its JavaScript and it's working asynchronously in the meantime with what it does have in hand in memory as it's continuing to grab these resources down well while that's going on the browser is beginning to construct this object based representation of the HTML elements in the HTML page and it constructs them into a series of objects that are called nodes so it'll create a node for a given paragraph a node for the ID of that paragraph a node for the class attribute of that paragraph a node for the text that belongs to that paragraph you can see where I'm going with this everything gets its own little instance of an object and ultimately it's building this object graph that represents all of these these elements their attributes and their values the text values and so each element node could contain other element nodes as well so a paragraph could conceivably have some div tags or probably more likely vice-versa a div tag has a paragraph a div tag has a header has an unordered list which has list items and so on so there's just that nature of HTML and the the object model that's being constructed in memory has to consider all those kinds of relationships as well as the attributes and the text values of each of those attributes so at any rate the final result of all that work is this rich object model that represents the document that can also be accessed programmatically we'll talk about that in just a little bit but at some point the browser considers then all the styles that it has downloaded whether embedded in the HTML page itself or through one or more CSS files that have been downloaded as well and it also has to consider any of the default styles for elements so these are ones that are baked right into the web browser it starts to decide which styles will overwrite the other styles which values will overwrite the other values and so now it has to then start to apply those styles to the various nodes inside of this large object graph of node objects and once it's kind of settled on which styles to apply to each of the individual nodes it then has to calculate how much space each of those will take up on the web page so that it can essentially at some point visually render those on to the web page for the end user to view the next thing that it's going to do is it's going to start to parse through the JavaScript that it's been downloading from various files and it'll determine what needs to happen and when it needs to happen so some code can be executed immediately some code is attached to the various events of the various nodes in this object graph of nodes that represent the web document and we're going to see this in a little bit it'll impact how we write our code and where we write it in the HTML document so when we're talking about this collection of nodes from a programmatic standpoint as well as the entire API of the methods and properties that we can access programmatically to change things about the nodes that represent our document to modify them to add new nodes to remove nodes things of that nature as well as the web browser as a whole and all of the functionality that it provides to us like the ability to create things like the history the console window and any of the other debugging windows that might be available take all of that into consideration and that is at essence something called the document object model or the DOM and so we'll talk about the DOM in the remainder of this video in the next couple of videos but eventually after taking all those things into consideration then it finally will render the page visually to the end user but its work is not done at that point now it's listening for the user's interaction with the various nodes inside of the document and when the user interacts it might click or hover or mouse up mouse down it might use a keyboard you know the user can interact with the various elements on the page in various ways and if the software developer or the web developer has attached event handlers functions that should be called in response to those interactions those events then it will the web browser has to say oh yeah we have these two functions that we're going to call because the user clicked on this button go ahead and execute those those two functions now so when we create those associations HTML actually gives us a couple of ways to do those create those associations but we're going to look at some programmatic only ways to create those associations talk about that in the next video but at any rate as developers we can also interact with other APIs that are exposed to us for example most web browsers expose the console window so that we can write to that write little error messages out like we've been doing up to this point so we're primarily interested in the document object model as javascript developers again it contains an object graph that represents every element the attributes of those elements the text that might be associated with those elements and the relationship between two elements you know one might contain the other or they might be siblings and so on each of these objects are referred to as nodes as I said earlier and I just want to make the point really quick that when we're talking about nodes inside of the document object model that shouldn't be confused with node js the environment that we've been using up to this point to execute our this little javascript examples they're completely different they have no relationship to each other alright so at the highest level you have the document node and the document node will contain one or more element nodes and each of those could contain other element nodes but each element node will probably have some attribute nodes associated with it and maybe a text node associated with it okay so the DOM also includes a rich API so lots of functions that we can call in order to access the various nodes their attributes the text and so on alright so we can find a specific node or a collection of node that match our criteria and then once we have a programmatic handle to a given node or multiple nodes then the API also gives us some functions that we can use to modify the values of those nodes everything from changing the text of a node to changing the attributes of the node like changing the class that is associated with that given node we can remove nodes we can add nodes all that programatically the API also allows us as I mentioned a little bit ago to associate events that are raised by the web browser usually because the end user triggered the event with a mouse over a click whatever the case might be as developers we can associate our functions with those events and then finally the API provides some helper functions to perform various various things one that comes to mind is network operations like being able to call out to another web server to grab data or to grab some other code that can be executed but finally there are several ways that we're going to talk about in this video to basically write your JavaScript in a web page or associate your JavaScript with a web page and if you have professional aspirations then you should be aware that not all of these techniques are smiled upon in fact most of them are frowned upon there's one that's not so you might see some examples and here we'll just add this to our to our existing page here that I just created randomly in DOMintro.html and I'm going to create a button and in that button I'm going to say click me and then here I'm going to add an on click equal I believe we've done this already right but I'm just going to write some JavaScript right here now using this technique I'm able to pop up box an alert box in the browser to just kind of execute one little simple line of code so let me see how I'm going to do this let's right click on this and let's reveal it and explore and from here I can double click in it should open up my default web browser I click click me and I get a message box an alert that pops up with the little message the site says hi okay and I can also do something a little bit different this might be a little bit more akin to what we've been doing console.log and I could do hi in the console all right and let's just refresh that page so I'll hit refresh I'm going to hit F12 on the keyboard this will allow me to see the console tab and specifically I want to look at the logs when I click the click me button hi in the console okay so hopefully that all makes sense now using this technique you're only going to be able to write one line of code at a time maybe two you might have to write some you know but there's no doubt that just keep writing a bunch of statements here inside of this on click event right in line in the button is not a great idea so your other decision is or a choice is to actually add a script tag like so now for reasons that I'll explain a little later typically you don't see script tags added there you would probably want to put them at the bottom of the document and the reason is pretty simple that the that the web browser is going to look at the code line by line and if it encounters a script tag up here and we reference elements in the body those elements may not have been loaded yet into the document object model if we put the script at the very end we can ensure that everything above this has been loaded already so we can reference the various elements in our html the various nodes in our document object model to save in a more programmer friendly way ok so here's what we can do instead I can actually create a function let's call this just a click handler and you know I could even just add a message and here I can just do something like console.log hi and then maybe dot dot dot and then maybe message like that so now in the on click I can kind of wire this up and say hey call click handler and I'll just say from the button click event alright so we'll save all that and with any luck you can see where we make the call to the function we've created and then passing in a message which we'll should display in the console log let's open up our web browser again let's refresh this page f5 click the click me button and we get hide dot dot dot from the button click event alright so you might be wondering well wait a second you are calling a function before it is defined in your javascript isn't that a problem no and this is something I wanted to talk about before in the supplies whenever we are executing all of our examples in node function declarations are hoisted to the very kind of top of the execution environment so the javascript compiler will go through and look for all the function declarations it will put them at the top it knows where they're at now and then it will continue to execute any additional code so this is in essence added then to the top of the execution chain so by the time we get to the click event handler for this button javascript is already very aware that this function exists alright so small point there but these techniques of using this on click equal and the script tag in this manner these are generally frowned upon professionally you probably want to do what's called separate your concerns so your javascript may be more appropriate to keep it in its own file and to kind of remove all of these references like this that we have there so I'm going to say don't write javascript in your html page alright and some people might argue with and say it's perfectly fine and you know it just depends on how much javascript there is and what your professional aspirations are and the other programmers and what they're doing in your group but generally speaking what you want to do is kind of just add your code to another file in this case I'm going to create another file I'm going to call this domintro.js and then what we're going to do is actually wire up the event handler to to the button click event but we're going to wire it up in our code so what we're going to do to start off with is to create an iffy so remember how we to do that we're going to create function we're going to wrap it in a parenthesis and then we're going to say execute immediately alright and then here what we'll do is we'll define our function of the click handler and then I'm also going to let's go here to our domintro.html I'm going to give this guy an id and I'm going to say your id is my button alright in fact I hope you don't mind that I'm going to delete all of this out of here alright I'm going to delete all of this out of here it's gone now and I'm going to go into the domintro.js and the first thing I need to do is get a reference to my button alright or my button so what we'll do is let my button equal document dot get element by id and then give it the id I want my button button alright next thing I want to do is go my button add event listener I'm going to say which event I want to listen to in this case I want to listen to the click event and when that happens I want to call click handler and I guess I could pass in a message if I wanted to at this point so hi from my iffy right now I need to go back to the domintro.html here I'm going to add a script tag like so script type equals text forward slash javascript source equals and then we'll give it the name domintro.js and so say that and now hopefully load this guy up refresh and you can see I did something incorrect let's go back here let's get rid of all of this business right there alright now we don't want to call that method just yet we just want to wire it up to the button and say whenever the click we want to listen for the click event when that happens then we want you to execute click handler alright now that we have that in place let's go ahead and refresh click me and there we go now we get pointer event not exactly what I was looking for if it's really important to us to pass in the message which I actually forgot about sorry what I'll do is just kind of wrap this call inside of a function expression so go function like so and inside there we'll make the call like that and then hi from iffy alright that should work hopefully so let's save it let's try that again there we go that's the that is what I wanted to happen okay so had a lot to say in this video about the DOM and about how to attach your JavaScript into a web page and still access the various elements of the document object model or this document object by using helper methods like get element by ID passing in the ID and now getting a programmatic reference which we can then use to add or even remove event handlers to in this case I'm just adding a function expression to make a call into another function that I created earlier alright hopefully all that makes sense and we can continue on in the next lesson and kind of expand on this alright we'll see in there thanks in this video we're going to talk about working with the DOM specifically how to access DOM nodes how to change attributes of those nodes how to add nodes dynamically and more so in the past I've created like three or four lines of code and then we would look at look at what those lines did and I wanted to change my tactic for this particular example to show you something a little bit more interesting a little more compelling so I've already created a DOM nodes HTML DOM nodes and DOM nodes JS and you can see here that I basically created just a little playground it does nothing of practical value it's completely contrived but it will show you how we can manipulate various DOM nodes and their attributes and you might find some of the the practical side of this how did I accomplish that useful as you pick apart this program and we'll walk through here in just a moment but again this does nothing useful it has a click me button a series of div tags each with a color and the name of the color itself and then a number beneath that and I'm just going to click the click me two or three times alright you can see that several things are happening all at once first of all we are changing every time the click me button is clicked we are changing the selected color div you can see the selections change because there is this thick bottom border applied to that particular div furthermore that color is applied to this number and that number seems to be growing each time we click the click me button so here we are going to click it we go to pumpkin what happens when we get to the end of our list of colors and I click the click me button one more time we start back over at the beginning of the list and so I can just continue to click this the number is growing I'm using relative m's, rems in CSS using it the number of times I've clicked it that's the number of rems that I'm applying to this font and so you can see that things are changing they are very dynamic and I just wanted to kind of it's a large enough application to be interesting small enough that I think you can pick it apart and kind of understand what's going on and that's really the intent here so let's take a look at the source code itself and we'll start with the HTML there's really not much interesting here I'm pulling a font from the Google fonts and then I'm also applying a style sheet the style sheet itself not a lot interesting in it and I don't want to take too much time it's just making everything look a little bit nicer than our previous examples here we're looking at the result container and that seems to be where we have the basically the white area with everything else inside of it this button this row of divs and the number and so you can see that each of these have IDs applied to them the click me is my button the color did will contain a series of child divs and I'll talk about more about that more just a moment and then the result is where we add the current number of clicks that continues to grow and grow here we have our script reference to domnodes.js that's where all the magic happens first of all you can see that I've created an iffy here and I can roll it up using the little plus and minus right next to that line of code in line one you can see that I've created a couple of functions one called increment counter one called update UI and then one called handle click you can see that I've initialized a variable called counter to the value of zero here I'm getting a reference in line 74 to the button and then I'm wiring it up like we learned about in the previous video to every time that the click event is raised for my button I want to add an event listener here we have a function expression that will execute both the increment counter the method that we looked at at the very top and then the update UI method that we looked at it was right below it this is where a lot of the magic happens so we'll look at that in more detail in just a moment then here you can see in line number 80 I execute update UI in order as the page loads because again as a immediately invoked function expression I want this to happen as soon as this file is loaded into our HTML by the web browser so let's go here to the top and we can see increment counter is very simple it just takes whatever the current value counter is and increments it by one now update UI is where a lot of the magic happens first of all we start off with an array of color objects each color object has a name this is the name that you saw printed kind of in the top middle part of each of the div tags as well as the color value itself and I just grab these from a website that has colors I think you see the colors I'll give you the site in domnodes.css alright the first thing we want to do is grab the result this is where we're going a reference to that element and we use the ID resultive to get an access to it so that we can programmatically work with it this is the div that will contain the current number of clicks not only will we increment the display the incremented click number but then we will also change its size and its color attributes as well next up what we want to do is then set the intertext attribute or property of the result object so this resultive we're going to set a property called intertext that's how we're able to put one two three four inside of that tag here at the very bottom of our white section of our web page and then so you can see this is one way that we are getting a reference to a dom node or a dom element and then changing the attribute we're changing the text whatever it was we're overriding it with the current value of counter then what we do is additionally access the style of that div so here we're going to the style object of the result element and then the style object has a series and I can hit the period of the keyboard to look at the intelligence all of these are attributes or properties of the style object for our div tag we can change all of these attributes if we want most of them are visual in nature and here I just want to change the size of the font taking the current value of the counter and appending em to make it larger each time that em being a unit of measure in CSS all right so that's how we're making the changing the number of times that the button has been clicked in that div tag and then also changing its size every time we click it okay so next up what we want to do is determine what the current color is in our array of colors so here's what we do we take the current value of counter and we use the modulo or modulus operator which will give us the remainder so if this has been clicked six times and there are six elements inside of our of our um array of colors that we define as a const here at the top then the modulo would be zero there would be zero remainder so we would access the first element of that array and that would be this alizarin it's that coral color alright and so we would use that so that's how I'm using and being able to kind of select each of the items I take the current counter so if it was two and there were six then that would give me a remainder of what a four so it would be the um we grab the fourth element from uh our colors array and grab the value property the value property of that particular object and set that as the result style objects color attribute alright moving on now what we want to do is clear out all the existing uh child color div so I basically tear down and recreate this list of colors by basically removing everything first of all from the previous uh call to update UI and then I begin to re implement it if the as I'm looping through each of the color objects to create a new div if it's the currently selected one then I want to apply not only uh the bottom border but then also use that color uh here I guess I already did that part but anyway um this is why I'm setting the inner HTML to an empty string of the color diff because I'm emptying out everything inside of the current div but now I'm going to loop through each of the colors and here I'm basically dynamically creating new div tags uh so I create a new div tag and then I create a text node with the name of the color for you know whether it's the first object the second object the third object I'm grabbing that name and creating a text node I append that text node as a child to the div tag that I just created I style it up and then at the very bottom here you're going to see I actually append that child uh append that node that I've been styling up to the larger outermost color div so I do that six times uh and if it is the currently selected item then I'm going to change the styling of that particular node by adding a class the selected class and that's what's going to add that bottom border in fact here if I wonder if I can just go to here and find selected so there we go it is uh just adding a bottom border of five pixels with no padding alright and so um that's pretty much it now you'll see that throughout I'm accessing the style object or attribute of the given div tag setting its width its height and other properties like float padding left padding top and I could have just created a CSS style and then added it using the same technique that I've used here but I chose just to demonstrate that we can get at all those those style attributes in addition to the style object there are other things that we're able to do to it like append a child to it so we want to we have a div tag and we want to append something to it we have a div tag and we want to append it as a child to that div tag which is already a child to a div tag child to the body right so hopefully this will help you to see how this whole process works and then we can basically get at any DOM node we can modify it we can add new child nodes to it um creating them essentially out of thin air and we can even do more like move nodes around if we really wanted to and so on obviously this example didn't call for that but essentially once we get a handle to an element then we can do anything we want with it um that we can conceive of so there are so many options that it didn't really make sense to kind of go through them in a laundry list basically this is a matter of imagining what it is you want to accomplish getting a reference to the element that you need to start with determining do I need to create a new element and append it on or do I need to remove elements that are currently child of the existing node um which attributes of that no do I want to change and so on until you kind of construct I mean it took me several minutes to build this example and it started really simply it started by can I just increment uh the current number of clicks alright I got that working now let's move on to the next thing can I create a bunch of colors and have them applied to the number can I create a bunch of dibs and apply those colors to the div and so you just keep working at it little by little until you've you know tackled essentially the whole application and that's how I built this alright so hopefully that was helpful as kind of a larger example that we're able to to dissect and understand better how to accomplish something that that we conceive of by working with nodes inside of the DOM alright so let's continue on I guess we're pretty much done so let's wrap it up in the next video see there thanks I just wanted to briefly congratulate you on finishing this course that's quite an accomplishment and that's awesome and I have to say that I definitely respect anybody who puts the time in to learn a new technology or new skills so you're awesome I congratulate you and I wish you the absolute best I sincerely hope that this course was helpful to you in some way and that you came away with some confidence in JavaScript and that you have a solid foundation now to build on and I'd strongly encourage you to keep pushing forward in fact modern development with JavaScript will require that you learn some of the most popular tools and libraries that are currently in vogue by the JavaScript software development community as well as the build and deployment process for JavaScript applications so I hesitate to recommend specific libraries and frameworks for you to look at because especially on the client because things are changing so rapidly in that space but I think you'd be safe at least if you're watching this within a couple of years after I've recorded to get started with something like view.js vue.js or react.js by Facebook if you're going into a corporate software development environment like at a big company then you may want to look at angular or angular I think the current version as I record this is version five I'm sure they're going to every six months they're trying to release a new version of that you're probably going to need to learn a little bit about packages in JavaScript and using npm or yarn another tool by Facebook you probably want to learn a little bit about webpack and parcel but again honestly I kind of feel silly recommending anything because a couple years from now it's likely that the JavaScript development community will have moved on past some of these sorts of things so you know at least enough now where you can follow along in those kinds of discussions and begin to stay abreast of JavaScript's frequent and fickle library preferences de jour now on the server side I highly recommend that you learn more about Node.js and if you want to use Node to create websites and web APIs then you may want to learn another framework called Express.js which sits on top of Node makes it easy for you to build entire websites just on the server side okay so quickly just want to give another plug to my own website here let me type it in for you developer university at devu.com devu.com I'm learning new things every day and when I do learn them I try to share them on my website so definitely want to come and check it out check it out every so often finally a quick thanks to Microsoft Virtual Academy you guys are awesome quick thanks to you the viewer for watching this and staying with it through the entire course and I as we close here just want to say that I sincerely and truly wish you the best hope you can leverage this course and do something really awesome and if you do let me know about it so good luck