Javascript tutorial for beginners Full course | javascript Full crash course for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
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 also 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 developeruniversity or devview you can visit me at www.devview.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 uh 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 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 the introductory material a little bit more quickly than what i plan on uh than 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 i 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 uh about javascript way back in 2011 the the course actually had a fairly long shelf life and so much has changed with javascript since then that uh i necessitated that i actually play catch up and kind of learn some of the new features that were added because i wasn't keeping my skill set uh 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 uh databases and and other uh 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 uh 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 you can go one of two routes you can either attempt to write your code in such a way that it is 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 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 come backwards compatible with as many versions of the various web browsers as possible then you want to check out a website like anatool actually called babel js so you can find it at babeljs.io and it will again use a combination of techniques to uh to take your code 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 babel in this course but you should know up front 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 going to have to take into consideration uh the fact that some people will be using older web browsers writing javascript that will run on a web server using a framework like node.js is a bit easier because well you're going to have some 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 uh as a as a lightweight means of executing these little tiny javascript examples that we're going to create throughout this course so you're going to 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 uh 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 going to 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 that's you know typing it yourself is the absolute best way to learn it starts to develop muscle memory you'll have many of those aha moments where you realize oh 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 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 going to 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 going to 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 going to ultimately want to know something from me i've recorded enough of these courses i know the questions that are already coming you're going to 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 uh where you can simply use them for free and find them in an instant uh if you want to get more explanation about any given idea that are that's covered in this course okay so let's go and get started i want to encourage you to take your time don't feel overwhelmed stick with javascript stick with this course and you're going to 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 you write code and you see it working and you're like wow this is awesome so i'm glad you're going to get an opportunity to do that it's the most fun you're going to have on a computer i promise and you'll you'll wind up enjoying it so stick 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 uh we're going to install the tools that we're going to 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 regardle regardless of which operating system you currently have installed so uh 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 going to 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 uh google chrome the second tool that we're going to need to install is node it is the 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 going to need an authoring tool something where we can actually type the code in now in the past i've used notepad to actually demonstrate because i didn't want to like you know recommend one tool over the other but then microsoft came out with visual studio code it's available on uh all three platforms so it's also available for free so no matter what you're using you should be able to download 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 going to 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 uh it's it's really good so i highly recommend it let's get started we're going to 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 going to open up a command prompt and i'm going to type in node dash 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 can 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 like the latest features you don't need that just 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 going to use any really advanced features in node so this shouldn't really matter much i'm going to go ahead and run it run the installer here what you see next depending on which operating system you're using uh will 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 want to 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 uh in my command prompt it'll it'll pop up okay so just make sure that everything is selected you'll be fine it's not that large next i'm gonna have to agree to um windows uac you might see something different here on the mac or linux i'm going to 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 uh the v8 javascript engine that they ripped out of chrome they added some tooling around it to support things for like http working with 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 going to use it for that we're going to 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 going to have to reboot my computer so let's pause i'm going to pause the recording of the video right here i'm going to 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 of applications where you can uh use the the command line tools to compile your code and things of that nature that's not something i would ever want to do it's great for web development and that's what we're going to 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 uh 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 going to 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 to the code setup wizard i'm going to go ahead and accept the agreement and we're going to 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 our code simple things like uh 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 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 going to hit close on that so what we'll do is uh 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 going to close down the welcome screen i am going to click open folder and i'm going to go on for me i'm going to go to my c drive and i'm going to 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 going to put some some javascript files and later some html and css files in that folder and we're going to want a folder structure so right here in the open folder dialog i'm going to right click and select new folder i'm going to call this source lowercase s and source and then select that folder now that becomes the working folder that i'm going to use to add additional files and and all the work that we do for this course inside of there here it doesn't really wants me to put get install git 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 isn't you're installed on you might see something different here in windows you see powershell doesn't really matter as long as you get a command prompt and here i'm going to 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 going to click on this little file with a plus symbol in the upper left hand corner i'm going to 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 going to 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 log and then an opening and closing parentheses inside of there i want to 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 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 going to come to learn writing code is an exercise in 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 want to double check and make sure there's not extra spaces you want to 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 all right 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 you use or you can just go file save all right now watch what happens when i just use the space bar 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 going to 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 control 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 dot 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 we ask some execution environment whether it be a web browser or in this case node to to take a look at this 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 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 we can access the file system ask 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 um with elements html elements on a given web page all right but we might also use javascript to uh 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 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 uh web pages uh and 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 run time what whether it's node or a web browser will 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 english class you'll know that there are parts of speech that that you're supposed to use punctuation at the end of a sentence to indicate the end of a complete thought they're nouns and verbs and adjectives and adverbs and and propositions 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 and with with uh i guess uh 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 task and even kind of arranging those paragraphs together to create entire applications all right 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 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 of 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 very specific about adding that semicolon at the end of 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 all right um 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 onto 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 and a statement usually consists of one or more expressions so uh 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 invocation operator or the method invocation operator it's those open and closing parentheses and we can even then pass in what are called arguments to those functions so 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 make sure everything is lowercase 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 and 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 lowercase 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 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.capital l log is not a function that's true it's because it's lowercase l and 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 you're relying on your the person receiving that text message to understand what you're trying to say the computer doesn't work that way it means 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 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 uh to tell the compiler to ignore 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's 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 forget everything 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 let 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 it's i'm going to go between the closing single quote and the closing parenthesis 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 and use the end of 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 you're 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 i promise you can too let's run the application see that we get the 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 you know or an advanced javascript developer just yet i'm willing to bet that you understood that we were creating a variable essentially uh a a bucket that could contain a value and immediately we set that variable equal to the value seven 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 assigned them in lines three and four and we know that 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 has double duty it's it's serving to be the addition operator but it's also serving to concatenate two values together in this case to string values together so that we can print it out the screen so we're going to use this kind of as a starting point and talk about this at more length in the next and 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 you 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 [Music] variables.js like so and then i'm just going to copy in the code that we had here we'll use this as a starting point all right 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 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 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 to store different values and retrieve those values back out throughout the 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 uh and let's start start talking about the parts of speech in javascript a keyword is something like let and we'll see some other examples a little bit later but essentially think of it like a verb in the english language it's a 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 all right 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 a area of storage uh a unit of storage is assigned to our application that 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 all right 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 all right we'll come back to that at the very end of this lesson uh now before we get too far there's actually a couple of different ways to 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 there's two ways to 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 uh 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 uh pretty challenging uh 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 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 uh 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 seven 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 six 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 a little carrot right underneath the equal sign and it says assignment to constant variable that's the problem and 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 six and it says can't do that okay 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 all right so uh just want to point out that we can uncomment out line number two as we assign the value of x to different values and we can keep doing this as many times we want to so at this point in line number one we've declared the variable set it to the seven then we've assigned the value of six then five then four we can keep changing the value in the computer's memory uh and what is the value in line number six what's x's value well the last time we assigned a value to it was four so uh the application now whenever we run it will give us seven because three plus four equals seven right so that's what we get in line number seven great all right so uh 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 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 seven again or let it equal eight 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 a variable once but you can assign its value as many times as you want to after that all right so in line number one 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 number one and two 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 one what is the value of x well let's let's find out console.log and 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 all right and that's generally not something we want it might be in some cases something we need uh but for the most part we won't do that it's preferable that at the moment of declaration you also initialize your variables if you can alright so that would be valid right there um all right 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 rule number two is that the variable names can contain letters or numbers dollar signs or underscores but no other special characters and you can't use a space uh in between you know two words that you intend to be considered together as an identifier identifier can't have any spaces all right and then rule number three is that you can't use any keywords so i can't do something like this let let equal to eight maybe if we try that we're going to get a weird error let is disallowed as a lexically bound name all right and so even if we were to scroll 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 all right 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 all right it doesn't it doesn't blow up so we were able to use x and assign it to 8 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 all right so let's just get rid of that but those are the rules has to begin with the letter a dollar sign or 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 uh be aware that uh 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 uh x y and z are not very descriptive names ideally we would use something like maybe um let's go down here so let uh 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's code and so on all right 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 appen or words that we append together should have a capital letter so you can see that i followed this convention every single time in lines 15 through 18. lowercase z and zip code capital c in zip code all right 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 across 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 want to do let zip code equals 60459 what we've just done while it's grammatically correct from javascript's perspective and those are two separate variables in line 18 and 20. we've introduced some subtle um 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 uh 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 in the next video when we talk about the values that we're actually signing into variables and their data types and we'll talk about that next see you 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 datatypes.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 equal 7 [Music] 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 seven so let's start off by just doing console.log and then we'll say type of all one word lowercase and then x and let's save that save it and uh 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 uh 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 uh 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 whoops not just z i want type of z all right 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 but i literally want h-e-l-l-o space w-o-r-l-d all right and so those are your three of your seven basic um 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 all right 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 and 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 or turned 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 because we said that it's the 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 uh before the very end 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 nine how do i make it treat it like the number nine 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 c-o-e-r-c-i-o-n dot js i think that's how you spell it and uh let's start off with a quick little example here so let a equal seven let b 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 b and then [Music] console.log answer and then c all right before we execute this application what do you think is going to be output uh when we run it what will the answer be all right get that in your mind and now let's go uh node and coercion and uh looks like we don't get anything at all oh i need to save it 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 in 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 moreover javascript realizes that it can't add a a number and a string those are it's like adding you know an apple and a car together it's not like making an apple and 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 its 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 um 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 uh change this just a little bit and um 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 intellisense and intellisense 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 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 pull parse float that would give me a number with decimal values but this in this case the the string that i want to use i know that it will only be a value without without any decimal point 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 parentheses for reasons i'll talk about later so i'm just going to do an open parenthesis well didn't do it for me well there we let's just go ahead and use the tab key instead all right so the tab key will give me what i want now i'm inside the the parentheses that 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 um to use like a hexadecimal i might give 6 but in this case i'm going to give it 10 because i want to be a base 10 or a decimal conversion all right so that'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 this 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 four and five like we had before let's see what we get this time the answer is 13 just as we had hoped all right so the parseint 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 all right 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 i'll 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 or even a string that will not convert into a numeric value especially one that's decimal so i'm going to save this well let's go ahead and console.log it and d so let's go that and then we'll do this all right 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 um we could actually do something along these lines as well [Music] let e equals is n a n and then i can give it some numeric value in this case i'll give a 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 that's printed out all right 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 or convert one data type into another all right unfortunately there's no parse boolean so you can't take a string of true or false and convert it into a boolean you'll have to take a few extra steps there's a bunch of of examples online for that and so depending on the type of conversion that you're attempting to 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 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 and that an expression is made up 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 things like keywords 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 we'll learn about functions soon and functions are another type of operand and so unlike keywords and operators in javascript which are fixed and part of the language we you 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 said hey uh the dog some 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 uh proper we have a noun we have the dog but we don't have any verbs or adjectives or adverbs describing or or um you know kind of giving us more detail about the dog the same thing is true with javascript so we can't for example 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 uh because the javascript compiler will say okay what do you want me to do with that uh 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 all right 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 all right and even in this little tiny um 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 all right 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 [Music] number one variable declaration i think i spelled that right all right so let's go ahead and just move that up to the very top and say this is bad uh and then we'll do something like this i kind of like doing some ascii art there whenever i create lists inside of my code all right 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 uh and then another type of expression is to perform an evaluation that returns a single value and 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 um and i'll just comment this out because i want to reuse a there we go good right so here we go line number 16 i'm going to go let v equals 3 let c equal 2 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 all right well let's identify them so number one we're gonna see that uh let a so that's a variable declaration 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 all right 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 gonna go uh create a new file called operators dot js and so um there are several categories [Music] 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 it 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 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 um there's also the division all right and then there are some special ones like um 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 used out of context these don't seem so interesting but what we could do is for example um let's go var a equals one a plus plus and then console.log a all right let's save that and then go over to our terminal and i'm going to do node operators all right 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 print it 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 to 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 all right 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 all right so let's save 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 all right just something to keep in mind all right so that's increment and decrement um there's also going back to arithmetic there's the modulus and this will give me uh the 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 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 three equals three with one left over that one is the modulus all right and actually this becomes a lot more interesting and important when we're looping through lots of values in every like 10th or 20th or 100th item i want to print a little message to screen to say hey we finished processing the the 10th the 20th the 30th the 40th the 50th item all right and i use that actually frequently so i'm a pretty big fan of modulus let's comment that out so uh moving on to the different categories of operators uh let's talk about um 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 and allow them to be appended together to create one new string other operators precedence so we might uh you know order of operations we actually use this quite a bit even in non-mathematical situations so for example um let's just do var b equals uh one plus two times three 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 two times three plus one so that would be seven let's see if my 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 nine because three times three equals nine okay so we'll use this uh the um the opening closing parentheses for different purposes uh for example um whenever we want to do console.log these parentheses are also used as the um the function invocation operators all right 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 close parentheses to pass in arguments we'll talk about that a little bit later but again that is the open and closed parentheses um there are other operators uh and i'll just put them here they may not make a lot of sense at the moment but they will soon when we look at decision statements so there's the logical if i'm sorry the logical and in the logical or okay 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 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 and all these are are are used to um for various purposes in javascript uh and in most programming languages all right so i think that's all i really want to say uh let's pick back up in the next video you're doing great hang in there with me we're getting through uh some of the easy stuff and we're gonna start moving on to some challenging stuff here really quick but you're doing great see you 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 dot js and first of all it's 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 for 8 let's say 15 16 23 and 42. all right 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 and do 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 all right and then what if i want to get one of the the values i can just do console.log all right 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 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 four 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 so to get at it i'm going to use a and then right next to the a square brackets and then 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 the the variable itself so let's save our work and we'll go node arrays all right so you can see the first element of the array at index 0 gives us the value 4. the second element of the array at index one gives us the value eight all right 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 and it will print them all off for me just like i have kind of here when i actually initialized our array variable all right 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 a0 and i would set it equal to 7 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 4 to 7 because that's how we can access a single element and assign it a new value all right all right so um what about these mysterious uh 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 all right um so the other thing that's important to remember is that a array can can include elements of different data types so let me just do let c equals um we'll start it with four and then we'll do alex and then we'll do true all right so we've used three different data types right there and we can just do uh node arrays oh i need to actually do a console.log c there we go there we go all right 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 within with a 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.log a dot 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 one two three four five six so the question is is it going to give us six the actual number uh or is it going to give it 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 uh into play a little bit later when we use the length of an array and we uh iterate through each element of the array to print them to screen when we learn about looping all right so just keep that in the back your mind now there's a lot of strange things that you can do with with arrays and 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 um 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 then i want to do a console.log and a dot length like we just learned about and kind of see what happens here and then let's run that all right 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 four 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 um 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 seven total elements now i call pop three times it removes 77 42 and 23 leaving us with just four elements in our array okay so we're going to continue to use arrays they're a great way to to keep lists of things together and accessible and will 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 like objects and functions and we'll learn about some advanced use cases with arrays a little bit later all right so 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 alright 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 function 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 uh let's go ahead and create a new file i'm going to call this functiondeclarations.js all right 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 all right 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 it kind of represents a container relationship this code sits inside of or is part of or is rather the body of the function that we've just declared all right so um 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 call 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 all right 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 uh and then we use the open curly brace here and the closed 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 all right so uh 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 uh node and then function declaration [Music] and let's see oh declaration sorry there we go all right and we get hello so hopefully you weren't expecting something uh super interesting we're just printing out three lines with uh what i would call a flower box kind of a rounded some dashes to 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 a 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's 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 want 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 um here i'm just going to use [Music] some string operators here with name and make sure things are spaced nicely and so here i can do um whoops say hello to bob say hello to beth say hello to mr tibbles my cat all right 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 all right 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 uh 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 and 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 um 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 all right then i'm going to say let result just the name of a variable result be 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 a hundred dollars 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 a hundred dollar purchase it would charge eight dollars and 25 cents in tax okay 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 that value in this case a uh a number representing the amount of tax all right 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 get 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 all right and a good explanati a good use of that is uh whenever we need to create some code that should run 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 of javascript and if we use intellisense we can see that there's actually two input parameters to this function set timeout 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 in line 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 all right so here we go let's go and uh do node and then function expressions one one thousand two one thousand and you can see it prints to screen i waited two seconds all right now it's kind of hard to read it like this all in line 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 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 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 all right 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 at 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 you know 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 all right so but the 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 settimeout function all right so functions can take functions as input parameters okay so uh 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 uh 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 of javascript and pass in a new function expression all right 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 you using visual studio code to help me find the matching set of parentheses at the beginning and the end to pass in uh 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 i'm going to 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 calendar 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 that 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 uh now that you've run me run me again in two seconds because i'm gonna basically call set timeout again all right now i need to kick this off the first time we'll call set timeout once here on line number 15. and that will kick things off and then [Music] i'm going to hit control and c on my keyboard to stop the execution because it'll just keep looping and looping and looping all right 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 okay so let's see it run this all makes sense so i waited two seconds saw it run once all right twice three times and see it'll just keep going every two seconds until i hit ctrl c on my keyboard to stop its execution all right all right the last thing that i want to show you now comment all this out is that you can create a function declaration i'm sorry a function expression that says something like console.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 intersect that we use just to define input parameters we don't need any but we still need it 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 what four sets of parentheses we just have to keep them straight in our mind of 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 iife sometimes i think it's pronounced iffy all right so keep in mind if these and we'll come back to them a little bit later all right so let's move on and uh 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 invoke function expressions are okay all right so we'll come back to this and uh 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 we'll 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 the 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 but 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 we'll just hard code a value and then say um 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 uh that will that expression will return true if it's true then we'll perform whatever code we write here so uh console.log and count is four so the first time we run this we're not going to get really anything all right 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 all right 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 get the counter message count is not 4 this much we know to be true all right all right so count is not 4. 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 okay so there's actually several different variations of this we can use um 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 can maybe do a message like console dot log uh count is greater than four and i can do kind of the opposite as well else if count is less than four so console.log count is uh less than four i guess i 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 would never happen so it's going to save our work here and see this run count is less than 4 because it's 3. 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'll 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 uh are 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 uh 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 um 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 um super strength uh may also have x-ray vision [Music] alright let's add another case here and say case batman and notice that kind of the 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 our case against and then a semicolon and everything underneath that will become part of the body of that 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 alright 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's superpowers and they 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 a green arrow not particularly one of my favorite heroes and um 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 um green arrow is just a member of the jla okay all right one other quick tip here is that whenever you're evaluating strings um there's a possibility like for example batman what if we had capital b in batman all right 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 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 ternary 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 just a string or a number back depending on whether that expression evaluates to 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 i'll create 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 b and initialize its value to the string one all right so just a 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 b so two uh equal signs that are next to each other is the equality operator this is a check for equality to say does a equal b and if that is true then what we'll do is return the word equal as a string but if it's not true notice the colon that separates the true from the false will return the word n 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 um the result like so so now let's go ahead and run that and these are equal great um 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 all right 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 okay 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 another type of equality that we can check for and that's 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 uh it'll say are these absolutely equal even with the same data types all right and so in this particular case we should expect a different result these are n equal they are not the same all right 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 uh then i have to say no these are not the same because one is a number one is a string all right all right so let me comment that out and let's take do one more check here um in this case i'm going to use a different operator the not equal to operator so i'll use the word not in equal and not not equal and not unequal all right which would be the same as saying equal all right 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're different data types all right hopefully that makes sense all right so let's go ahead and stop there um and hopefully all this ternary operator business and and equality and strict equality makes sense and let's move on 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 arrays 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 four and then there are three parts inside of the opening and closing parentheses first of all [Music] 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 but 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 all right 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 to screen when we execute our script let's find out so let's go here and type in node iterations all right so we get an uh several it looks like 10 different values printed to screen each on a separate line 0 through 9 and then our application exits all right 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 uh this evaluation header for the four first of all we declare variable in this case i've declared i that's why we use the let but then i said well we don't really don't need it let's keep it short so we're declaring it and then we're going to um initialize its value to zero 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 the body of this for loop as defined with this a set of curly braces here and then finally after you've run an iteration increment the value of i by one all right 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 10 this this check is performed it's false and then we exit out of the program all right now let's do something a little bit more interesting like i suggested before let me comment this out here let's go um let a equal two and this should look familiar 4 8 15 16 23 and 42. whoops i guess i forgot equal sign there and now what we'll do is for i equals zero i is less than a dot length i plus plus inside the body of this we'll do console.log a and what element will we 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 zero based and once we get to for example the zero one two three four five so length will be six elements so once i is six it's no longer true that i is less than the length of this array and will 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 or one way i should say 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 this syntax and it can be a little daunting at first uh 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 four keyword intellisense pops up with a little window under it and i'll use the arrow keys to go to the for loop javascript all right there's a couple of fours 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 um of my for 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 is 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 i'll use the tab key one more time here it puts me to the 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 we'll just print out c okay 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 uh out of our of our array okay let's comment that out that's four and now let's take a look at the while loop um so we'll talk about the difference between these it may not be obvious at first but essentially we'll do this all right 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 1 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 and see what value what uh what the values that we get so we get one through nine that's expected and once we hit 10 we break out great all right 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 um 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 derive 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 four 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 pre-set 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 all right 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 all right in this case we've got one two three four five six once we reach the seven we circumvent this check and just say hey i want to break out of this all right so we can use that always to break out just like we broke out of the switch uh when we wanted to not let it flow through additional cases now the one thing i will say if you notice how i typed 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 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 that there's usually more than one line of code in this case there's just one line of code uh i could put it on the separate line and use some indentation like that or i can just keep it all on 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 it but stylistic for me this is so short i can read it all in one shot if x is seven 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 on the same line again i think it kind of is a stylistic choice that you'll have to make for yourself at some point all right 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 um uh some [Music] some code snippets available to them like if i find it here in intellisense you hit 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 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 a equals first 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 all right 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 and we 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 is 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 all right so we're gonna 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 uh 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 save what we have let's run this again and so we see first first the first time it's printed out and the second time that is printed out all right 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 going to 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 it 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 to kind of understand that we are in fact able to work with uh the variable that was defined in the outermost scope can we still work with it do it use it and change its value so i'm going to 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 all right so the first time that it's run this first console.log it will be the value first but 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 all right so i guess the moral of the story once again to kind of reiterate what we said when you declare 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 innermost scope it will not be available to outer scopes now one last thing and i'll kind of end it right here if 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 will 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 okay 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 all right so we'll continue on the next video see you there thanks scope is a topic that will 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 topmost 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 five or six lessons or so will 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 uh 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 one and inside of function one we can just return the string one right it's not very exciting but it demonstrates the point that you can use the return keyword to return a value to which ever calls that so for example let value equals one for example and what would we expect to be in our variable value well we would expect to print out the string o n e or one 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 to string one as we'd 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 we could just make the 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 um let's go back to this i'm going to copy this again and then let's go um console.log and then type of value all right and [Music] 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 one 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 all right so uh 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 uh 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 whoops 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 point of the function i can execute the function by just using that variable with our method and location operator right all right 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 uh a value right and that value can be any type so in other words let's 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 like so and then do something like let my function equal 2 now what gets returned to my function it will be this inner 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 all right 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. all right oops let me spell return correctly all right 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 give 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 um of what you're really working with and that's references whoops let's actually execute it there we go three what you're 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's pretty far-fetched you probably never do that but the fact is that what gets returned from our three 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 all right 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 the 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 and objects specifically all right so just keep this thought in mind and we'll continue on you're doing great hang in there we'll see in the next video thanks if you remember uh 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 that we haven't looked at 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 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 all right so um let me first of all start out by creating and you file object.js and so um you know 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 in the year and so on and i may have some functions that i need as well things like uh 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 to make the model of the year in a special format but i might define a car object like so so let's do um let car equals and then we 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 all right take a second and catch up with me there if 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 or object and uh the first printout is bmw 745li because we're printing out the make and the model of this car all right and then here i'm just getting the year of the car and printing that out in a console window all right so in this case this object that i've 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 cur a series of curly braces here this set of curly braces at the outermost level here this defines kind of the boundaries for the object and everything that lives inside of it is 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 three four and five here we have a list of name value pairs 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 you'll probably 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 745li and a literal number 2010 that represents the year all right and notice that the property and the value are separated by the colon character all right 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 all right 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 um 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 um 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 uh several lines here but essentially we're just returning a value or in the case of the second one just just calling console.log but we could write any uh number of lines of code inside of here these are just happen to be very simple for the purpose of illustration all right 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 that which i call the um the property access operator just the dot on the keyboard same is true when access of accessing a function uh as you can see here in line number 15 i use that period that member access operator and then you know 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 uh i i keep referring to these functions that are inside of a an object as a method and and i think you should 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 frankly 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 accessor to access a specific property here let me go ahead and 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 uh but it uses a an index so it's actually kind of interesting how this works um 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 of this lesson all right so i recommend you just use that dot notation for now and all will be happy so um 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'd 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 that opens up my understanding a little bit more to how objects work um i'll just give you a quick example of what i'm talking about here here we can create a 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 of inside of that well what i can do is just kind of just say hey i want to create a property here called whatever i'll set it equal to bob all right and it'll just automatically create a property called whatever and set its value equal to bob just like that no let or var keyword or anything if i do console.log um you'll see that card.whatever in fact will come out to be bob or i thought it would oh i think what i'm going to need to do is save my work here and then do try this again oops oh i'm sorry another car i had the wrong reference it didn't exist on car but we need to look at another car dot whatever and there we go there's bob okay so just an interesting feature of objects you can 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 all right um you can also do some other kind of interesting things might as well take a few moments and look at these so um 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 uh 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 um and so let's figure out how can we actually print out the a uh so console.log a dot my property dot 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 you know 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 and create essentially what becomes a namespace and we'll we'll reference that a little bit later when we talk about solving the global name space issue or or putting our variables at the at the global level of our of our applications which we're trying to avoid all right 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 all right 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 all right and that's perfectly valid so objects can 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 there's nothing forcing you to keep the same set of properties for any given object uh inside of an array of that of that object you know as long as your javascript code or whatever will consume this 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 all right just keep that in mind let me paste in some more interesting examples here just kind of get expand your thought process on 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 year make and model all right then i could iterate through the car lot and print to screen each of those individual car objects right so that's one example how about um you know if this was more of a 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 runs off the side of the screen a little bit but you can see here i'm creating a contacts object uh here's the start in the end and inside of that i have a property 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 tabor has two phone numbers richard bowden has two phone numbers and then but our employees like steve and conrad and grant well steve has two phone numbers but connor and grant only have one phone number all right 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 json or js json i guess some people put the emphasis on the on it's short for javascript object notation json 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 uh to store um settings or properties inside of um you know a more advanced javascript application or they use it in visual studio and c sharp projects to store application settings for example uh now in in the new version of c sharp and net um 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 all right so what was my point here well if you're familiar with what json 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 json just be aware 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 json 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 along 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 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 why 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 to 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 just is is consumed the entire time that that tab is open uh 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 these 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 included 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 the 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 and a lot of effort went again around trying to figure out how to solve this issue given the the tools in javascript that they had available um 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 start the 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 i 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 too 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 uh 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 five to ten years but there are some newer ways to to tackle this all right so any rate 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 five or ten variables that we'll 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 property variables and functions of that particular object that gets returned all right 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 we return and that's generally a good thing so there will be a couple of benefits that come out of this all right so um let's get started by creating a new uh a new file called uh module pattern dot js all right 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 to start off with we wrap it in a set of parentheses and then we use another set of parentheses to actually invoke it all right 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.count 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 we'll take a couple of passes at that actually okay so um 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.log and um we'll just uh 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 get set to counter here all right so um we're going to start off simple we'll come back to this a little bit later because there's going to be a issue with one part of this actually this part right here what if i just want to return back the counter the current value 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 of increment property and it will return a function and inside that function we can do something like count plus equal to one and uh then we can call the our print method and then just say after increment something like that we can also here let me use comma right there because we're going to create another property of our return object called uh reset and what this we'll do is call a function so create another function expression print before reset then we'll call the count and then print or we'll set 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 all right so now we have basically our uh our module pattern we created a module which is essentially an iffy that returns an object that will expose functions and other properties like um like the current count and now here because i've invoked this immediately this is available it's already been executed and calendar now is fully populated and ready to be used in our application so i can do counter dot value i think wasn't that the name of it i've forgotten everything already okay value so console.log counter.value and um i could try to do console.log counter.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 first time we get it undefined wide because count is not a property of counter uh because we didn't ex it's not exposed and it's not being returned in the return object all right so that is impossible now what we can do however or we will try to do is call counter oops counter dot increment you can see it shows up in intellisense that's a good sign so we'll call increment in fact let's call it like three times whoops kind of ended up below where i wanted to go there all right great and then we'll call counter dot reset like so all right so let's see we get this time it's not gonna quite be as satisfying uh because we're gonna 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 it 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 we'll do something super simple it's just going to return count and then and i did it all in one line put it down on multiple lines didn't 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.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 all right this is a little bit more interesting well almost interesting i need to invoke get okay so 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.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 deals 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 um and mostly in in terms of functions that give us access to the private functionality and 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 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 uh 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 uh 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 um i'm going to call this reveal revealingmodule.js all right and i'm just going to paste some code in so that we can kind of compare and contrast the two versions all right so it's it's nearly 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 uh 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 uh functions by including them as properties in this return object so i can call counter dot get in counter dot 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 it 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 clear a cleaner clear 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 the get equals 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 um you can't really do it that's not possible okay so um 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 namespace 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 i wanted to kind of bring all that to a head all right so let's uh continue on in the next video we'll see you 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 now 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 uh 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 an 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 all right that's all it is um and then 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 dot js and uh 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 because that's kind of the point of this and it'll just say howdy and i guess we're going to pass in a name so howdy plus the name all right all right so that's really step one i create a function that returns a function looks like i've got a little problem here whoops i return a function there we go uh 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 all right so then i can actually uh make a call so for example let bob equal say hello and passing in bob now from this point on um i call bob well we'll see what happens here node closures all right howdy bob all right so um by itself it isn't all that impressive but that's really kind of step two and three all in one shot so i can pass in 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.log all right so this value is basically um saved off in a variable outside of the returned function so we're lying 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 um 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 in its own context from that point on uh in stored in the these separate variables all right so this is really uh just the binding process uh 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 so 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 four i guess you could say if there was a step four i basically use the new variable which represents a call to the method and a preset input parameter to conveniently call that version of my function now all right so um the important lesson to take away is that each closer closure creates its own what's called lexical environment and you'll see the term lexical used a lot in javascript uh whenever you're learning about scope i've tried 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 sayhello 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 right and that's just how the cool rules work like we learned about in scope basics.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 three through five 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 all right that's all you need to know about closures well for now anyway all right so let's continue on in the next video you're doing great see you 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've created a new file called this dash keyword dot js if you're pausing the video to follow along then you might want to go ahead and create this dash keyword dot 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 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 uh you'll see line number 10 and at the time i didn't even proffer an explanation as to what this dot make and this dot model actually mean in our in our application uh the fact is that this keyword can be a little bit challenging uh so even people with a little bit of javascript experience from time to time get a little confused about 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 uh 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 ja 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 this keyword to a given context uh and we'll explain what that means based on how you call the function all right 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 car dot print description all right 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 this keyword represents all right you're going to learn in this video at least that there are other ways to call a method that allow you to set or rather bind 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 and it's awesome it's a little bit over my head at times so i'm going to give you an absolute beginner's 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 off 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 uh beginning and an ending uh code comment character operator to whatever you have selected so that's a nice quick way to do that great all right 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 um 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 the most basic context of things that get uh executed inside of so when we create something in the global namespace a global variable we would create it essentially attached to the global namespace it's available everywhere in our application all right so let's see 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 all right so when i call the first method basically from the global context because i haven't created it inside of uh using the module pattern inside an iffy remember what we talked about previously so i'm 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 all right 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 all right 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 you strict there's a strict mode in javascript we're not going to go into it much but this will change how this keyword is bound and so if you have used 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 all right well i happen to know that it will equal undefined and that is a true statement what gets returned from this when we use you strict is an undefined value it gets bound to essentially nothing all right so just keep that in the back your mind this the rules around binding to this keyword change depending on the context in this case the context is you strict it will fundamentally change how it works all right 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 this um use 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 all right again in node this has special significance if you're doing web development it's actually window and we'll look at that here in just a little bit all right so now let's go function third and we'll return this dot value and then we'll do a console.log third so by default what do you think will get printed out will 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 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 all right 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 save that here let me actually comment this one out save it and let's run it okay 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 called on you know bob but this can also take an array here in the apply which could include bob so let's just do this see what we get i haven't tried this beforehand so yeah object bob okay 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 okay 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 all right that's the only difference okay but let me just kind of annotate this and talk through it just for a moment so just to kind of recap this 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 all right 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 kind of 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 refine this the difference is how the additional arguments are passed in like i show you here okay 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.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 this keyword because this represents this context all right because i'm calling print description using the car object all right so to call the function i would use the object reference that object reference car gets bound 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 [Music] and shift alt in a and so let's go function fifth and uh here i'm gonna go console.log and this dot first name [Music] and a space and this dot last name and hopefully this will make a lot more sense all right so now what i want to do is create two objects so let customer1 equals and they'll go first name colon bob last name colon tabor and then i'm going to create a print property that's going to point to the fifth function like so all right and i'm going to copy this and just duplicate it i'll make this customer 2 call this richard bowen [Music] all right and then finally we'll go um customer two dot print customer one dot print all right so now look at how this works what is the context how do i call the print method that's pointed to fifth well in this first case i'm using the object if it'll let me get in there object customer 2 that is the context we're going to bind this keyword to customer 2 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 object's 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 all right so now what i want to do is kind of stop working with node for a little bit and look at this keyword in the context of a web page so i've created a new this dash keyword dot html um i can use the term doc you can see that when i type in the word doc it's an emmet abbreviation if you're not familiar with them it just search for it online it's basically 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 here 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'll give it a 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 uh a value to be passed in and then i'm going to print out whatever that is to the console so console.log arg all right now we'll come back to this in just a moment i'm going to leave a space and go console.log this all right 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 this keyword all right so if all goes well here i should just be able to right click on this and say a reveal and 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 an 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 now click the click me button and we'll see the results of both of our console.logs in the first case what we get back is the this that was passed in as arg and printed out directly to screen and so in this case the this keyword will reference this entire element all right so let's take a look at that again here you can see how button on it 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.inner text and if you're familiar with web development at all you would expect to see what there let's refresh the page click the click me button again and you see click me all right that's the inner text of that button so i'm able to get to all the properties of this button but the key here is that that this keyword represents this entire button and i'm passing this keyword in so that i can look at this entire button inspect it 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 object's 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 uh 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 inline 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 here the click handler so it defaults to the global object the window object okay 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 and other programming languages but it has to do with how a given function is called and the site from which it is called so 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 all right 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 alone 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 all right 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 use of this keyword in a browser once again what this is bound to depends on how it's being called and who is calling it all right so hopefully that clears up what this keyword is i've given you a lot of examples i've tried to speak a little bit more slowly and and hopefully you can wrap your mind around what this actually is and um hopefully from this point on you'll be able to identify uh what this is in your code all right hopefully that helps all right you're doing great hang in there we're getting close to being more we're more than halfway done and you're doing awesome see in the next video 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 d structure ring dot js all right and the first thing i'm going 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 you recognize some of these names all right and then next up uh let's start by just destructuring this names array into um a 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 you know c d and i could even change the order instead of um d and e i'll go e and then d all right and so let's just do um console.log a console.log b and then console.log d because that's a little bit more interesting now we'll just go ahead and print out c as well why not and then we'll go e all right and so here we'll go node d structuring all right so take a look at what happened we have this array we destructured it down to a set of individual variables and we start off with a representing david the first element of the original array eddie 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 all right 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 all right so that's just one example there's some other interesting ways to to work with this let's uh let's just go here i'm going to take all this alt 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 all right equal names so now um console.log a console log b and then let's see what gets put out into others all right so this time a is from david b is eddie just like before but this time i said basically everything else just go ahead and stick them in a new array called others all right so that's what we see here printed out from line 21 we get this array representation in our console.log including alex michael and sami together all right 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 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 object in objects and you're destructuring out 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 all right 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 here let's start off with just saying let year and model then i'm going to 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 let's say it's bmw model will be a 745li year will be 10. the value will be 5 000 all right 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 and 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 and my model it'll be that value there that i'm pulling from the original object and printing it out so let's see what we get all right so 2010 from line 34 and the 745li from line number 35. all right 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 all right so hopefully that made sense 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 [Music] literals.js inside of here i'll do something really simple uh let name equal bob all right that's not the template literal this will be console.log and now i want to use the backtick 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'll you don't need to shift the backtick key all right usually above the tab key on your keyboard and so inside of there i'm going to use hi and then whenever i want to add something variable that will get kind of injected in from the outside it'll be interpolated from outside of this i'm going to use the curly braces and right before the curly brace i'm using 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 a node template literals like so and i get high bob awesome so um the other cool thing about temple 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 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 all right 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 gonna hard code this to return the value one all right 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 backtick character give me dollar sign curly braces we'll come back to those in a minute to try this all right inside of 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 1. and here's where the ternary operator comes in i'll say one good reason otherwise a few reasons all right 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 1 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 all right so you can 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 the string that gets outputted to for the end user based on a quantity all right 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 all right so doing great let's continue on see 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 or they're often just referred to as regex or regex are not exclusive to 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 you know 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 you know can impress people at parties based on that knowledge so um i 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 some 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 and cobble together your own little regular expression but i'm not going to pretend like you're you should go out and memorize any of this i know people have done it but 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 uh regic 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 all right super super simple pattern you would 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 all right 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 um i want to print it out and then i want to console.log see if we're working with a new data type or is this just a data type that we already know so let's go um node regex and uh looks like just attempting to print it out will just be a string representation of the pattern the type of the pattern is object okay 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 one an instance of that global object for uh regex patterns okay so um 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 we'll go up this is x y z a test all right and so what we can do is there's a couple of um 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 the console.log and we'll use our pattern dot 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 xyz in that string so let's save it um 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 this string so let me comment that out the next thing that i might want to do is actually replace that pattern that 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 um 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 all right like so this is just a test so i've removed xyz and i replaced it with the word just by using the replace method of the string passing in the pattern and the word okay there are a couple of other things those are the two that i find myself using most often here you can do something a little more interesting i guess log value 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 uh into individual characters at what point in the string would we find an instance of that pattern match so here we're going to pass in uh the pattern itself so i'll save that and you can see it gives me back this 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 the beginning of that pattern is found at the ninth character uh index eight oh i guess it would be seventh character character index eight right so um at any rate and then the original input was the entire string itself so we can actually um modify this or you know actually grab that object out and work with it individually so value dot match 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'm going to go match dot 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 replacement logic if i wanted to do that i'm not sure i would ever want to do that okay so 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 regex and then if you're lucky bing will pop it up to the top uh 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 up votes 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 that and there's plenty of references out there i prefer the developer.mozilla.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 okay 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 uh in the latest version of javascript probably won't talk about that in this course but um 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 uh regular expressions and let me just create a new file here called natives.js whenever we looked at the the regular expression lesson um we did something like value which is a string set to this literal string this is xyz a test and we did value.replace well how is it that this value has this dot replace method we really never address 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 all right and then if we were to save this and then um 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 uh 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 uh but what i'm about to say about strings is true whether we're talking about numbers or booleans or other other primitives that have an equivalent uh native associated with it all right 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 a string function capital or uppercase s in string but isn't that bad form didn't you didn't you say bob that we should create our methods with uh camel casing and so string should start with a lowercase s uh 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 your mind we'll come back to it all right so whenever we run this as you can see here when we ran node 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 um i'll 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 okay so and while we're looking at things here um 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 all right so again what's going on here is that these built-in native types provide extra functionality like this tostring method like this replace uh 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 is a list of those built-ins those natives all right so it includes kind of corresponding to the primitive string lowercase s and string number boolean there's also an object a function in a symbol and then 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 uh for important features but are essentially just objects whose methods implement a lot of logic uh for their features so things like the date function and the error function we'll 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's compiler is coercing is 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 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 all on its own so in this case let's just kind of see what what happens here just out of curiosity let's get the type of here we'll put the type of there all right 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 all right 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 two lowercase 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 all right so it's recommended that you stick with 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 and the pro its 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 here let's take a quick example and let's go ahead and move away from strings and just to numbers but the same idea will apply no matter what so 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 all right so at this point let's do a console.log and let's find out what the type of number my number is have 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 okay 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 will 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 equivalence but it's not really necessary so you know 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 car that the literal car that we created in a previous lesson here with the make model and the year property uh 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 gonna name a car and it'll have some input parameters uh 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 uh bmw 745li 2010 all right 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 and year populated all right 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 gets kind of becomes the context for this function call and so this empty object starts receiving new properties on lines 8 9 and 10 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 modeling your already set all right 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 or 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 all right it creates a uh 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 uh and it says to the function first before you execute i need to create an empty object and give that to you into 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 it could use it like we have in eight nine and ten here all right 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 i'll just do something simple like hey uh i am a simple function [Music] right and then we're gonna go var my function equals new my function and then we're going to go console.log type of my function [Music] 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 um so let's all kinds of problems with that line of code but i caught them before i executed it so that's good all right so you can see here in line number 21 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 a 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 all right 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 um kind of 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 all right 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 all right so what about this upper case 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 uh 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 some properties on it or maybe add some methods as the case might be all right 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 functional new functionality like the two uppercase uh the two lowercase the length property and others that we'll learn about but that's why they're defined as uppercase s in string uppercase n in number uppercase b and 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 uh 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 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 um with the new keyword and uh calling into the function all right so doing great let's continue on see in 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 and 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 furthermore 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 all right 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 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 um they can't be changed over the lifetime of any objects that are instances of that class so here in in object-oriented programming uh languages based languages like c-sharp and java classes are the focus javascript objects are the focus c-sharp java c 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 uh 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 into 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 it 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 uh kind of 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 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 uh between objects and how they're chained together it's a sub uh subtle but important distinction between javascript and other and traditional object-oriented programming languages so some people use the term javascript prototypal inheritance all right but i've tried 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 objects linking to other objects or ulu o l o 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 uh their pros and cons depending on what you're trying to accomplish the given problem you're trying to uh to solve so what i do want to do is have a better thorough understanding of how you know objects linking to other objects actually works 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 all right so this point if we do for example console.log new car dot make for example so let's um 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 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 all right 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 dot get prototype of and inside of that method i'm going to say 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 745li in the years 2010 all right so it's pointing to this original car so let's do this instead we can actually get a reference to my prototype get prototype of passing in new car and then i can do console.log my prototype dot 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 four now let's go console.log newcar.doors all right 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 uh 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 okay so console.log new car do you have your own property called doors and that's false all right 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 um here in line number nine it would find the prototype that new car links to and see that if it has its uh make property so we know that the new card 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 all right so we are changing the property or we're 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 card you have a property called make and new car says yes i do now i have my own property called make and it's set to the value audi all right so no longer do you have to continue and look at my prototype to find the property and its value you could look at me and find the property and its value all right 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 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 all right 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 going to hit a there and we'll get rid of all this just so we can kind of 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 whatever property it's prototype object doesn't have a whatever property and its prototype is undefined and that gets returned okay 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 kind of understand what we're talking about here 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 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 all right 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 prototyped prototype chained 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 from 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 okay so in a nutshell let's talk about what a class is and define a class it's essentially a way to define and create objects and so just like there are function declarations and function expressions now there are class declarations and class expressions so let's start off with just uh 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 okay so fairly simple and hopefully straightforward it's basically declaration you give it a name an 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 all right 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 year and just like in the constructor functions that we learned about a couple of videos ago you still use the this keyword a google make this dot model equals model this.year equals year okay so you can see similarities here right and then uh 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 745li and the year 2010. okay 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 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 all right 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 all right so you can also create methods on the class um in fact let me do it outside of the constructor method so here i want to create a print method [Music] and you know i can do something like console.log and then i'm going to go ahead and use our special sends string syntax interpolation syntax let's make some space for myself here and i'll say uh this dot make this model and um i'll format it a little bit with some parentheses but inside we'll go this dot here all right so here again now that i have an instance of my car class called my car i can call print like so and so let's go um node classes and you can see i get the nicely formatted version of the information in my car class you 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 at the very bottom and i want to create class sports car and i have to use the keyword extends car all right so right off the bat when i do that and i create a new instance of sports car let's do that so uh let my sports car equals new sports car now i don't have a um i don't have a constructor function defined but when i use the open uh the open parenthesis 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 defined on car and i can still set the make model in the year so um here let's go um [Music] dodd whoops 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 um at this point and we can even call my sportscar dot 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 to find in car we're getting the print method to find a car but i can extend and push beyond the boundaries of the car's 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 rev engine which will be a unique printout of information so console.log and we'll do something dot vroom goes the this dot model okay so now i can call my sports car dot rev engine and i get vroom goes the viper i guess i should have out of the space right there all right now what if i were to do this i still have my car can i go my car rev engine let's see nope can't why because it says rev engine is not a function well it is a function it's just not defined on the car class it's defined on the car classes inherited child called sports car all right so you can't access rev engine from the car class and you know what honestly there's more to it than that um there are some advanced scenarios but that should be enough to show you what cla uh 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's a mapping in that ultimately what's going on behind the scenes though is that we're creating a sports car object and its prototype is car and we're adding on a rev engine 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 uh 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 beat yourself up about it again this is a feature that was added for specific demographic people coming from other 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 stopgap measure for people coming from another programming language [Music] 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 what we looked at in the previous lessons but at this point just focus on um 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 to javascript and you know 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 all right so you're doing great just hang in there we're making great progress um you know the fact of the matter is that learning is is iterative and if this is your first attempt to 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 you know 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 a 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 the hump here all right 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 all right so you can see that i have a file called arrow functions.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 hi 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 will point to a body defined by an opening closing curly brace and then we'll do console.log howdy okay so far so good right one line of code an entire function declaration and we can just call hi so here we go let's go um uh node arrow functions and we get a simple word howdy printed out okay that's easy enough so let's comment that out and move on to a slightly more interesting example um we can actually go let hi and inside of the open and closing parentheses we can accept an input parameter so what these really are instead of using you know 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 or after the fat arrow and inside of the body i can go console.log we'll use our our special backtick character and we'll go howdy and then dollar sign open close and curly brace name add a few semicolons to the ends of some things here really probably don't need this one per say now let's call hi bop howdy bop 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 all right 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 dot log add 7 3 and we get ten 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 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 um well what is its pertinence and so i think that one of the ways that i and uh see them using 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 a method defined on the array built-in native object that we learned about but 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 let's 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 to marry these two ideas together console.log and then howdy name all right 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 okay pretty cool pretty cool let's take this one step further as we 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 equal zero 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 all right so now let's do uh save that get back to that so now david1 howdy eddie 2 howdy alex 3 howdy michael 4 all right all right 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 so start with names uh 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 see if we can get this all kind of lined up here okay so i'm re 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 all right and so you can see that what gets returned here because we're returning multiple values they get 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 howdy eddie exclamation mark and so on all right 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 all right pretty cool stuff all right we'll continue on the next video we'll see you 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 backfill 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 falsey 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 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 uh it's 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 all right and so if you just don't know what those are you're going to maybe perform 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's 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 we'll just look at these things but in the top these are things that are falsy well right off the bat 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 all right but then there are things like no if no well in and of itself no you know if we're looking at this completely subjectively null is not true or false it's it it doesn't really have a connotation of being true or false it's just null we'll talk about null later however it's considered by javascript to be a false c 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 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 false c 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 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 falsie 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 falsey 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 uh 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 an odd value that doesn't strictly return true or false it returns a null or undefined or not a number or zero or an empty string falsey it's gonna the evaluate the evaluation of that expression will be false but everything else is pretty much gonna return true okay that's all i needed to say uh in this video hopefully that makes sense all right we'll see in the next video thanks continuing the sentiment from the previous lesson where we're kind of doing a roundup 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 all right but here that's just a variable we didn't set it to a primitive string number or boolean or anything of the sort all right 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 x y z and we're going to use the strings match method passing in the regular expression literal that we created in line five but this time there is no match there is no string x y z 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 all right well what is the type of results type of result all right 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 typeof null equals object is you know it's it's basically baked in and grandfathered at this point but by all rights if if javascript had been designed correctly from the start that would be no but hopefully you'll get the idea there all right um 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 results and say are you you know and we'll do the strict equality uh strict equality evaluation is result null and if it is then we can say well no no match was found xyz was not found in our value all right and so this can be extremely helpful whenever we're uh building our applications all right 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 we're expecting an object reference but we don't have an object reference at this time set to our 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 all right 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 that 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 objects 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 23 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 uh the date but there's a couple of other ways um and uh let's just do like let bob equals date and there's a file system date type that looks something like um 1969 dash 12 for the month dash 07 and then t for time and then 0 7 because it's you know on a 24 hour schedule colon um 01 colon 23 and that's roughly about the same these these two will create the same basic time all right there's also we could just kind of simplify things a little bit here using a different format just just give it [Music] the year month base zero and day i think base zero as well though i haven't really i'm not really entirely sure about that um and then bob equals new date it's kind of the same thing [Music] 11 6 and then 7 1 uh seven comma one comma twenty three so i think these are about the same i may be off by one i forget if it's zero based or one base but you can look that up fairly easily i'm not gonna 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 var elapsed time equals n equals today minus bob console.log elapsed time and what will get back to me is the number of milliseconds all right between those two between those two dates so this is the number of milliseconds and i could divide it out calculate the years the months the days the hours minutes and seconds if i wanted to all right 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 dot get date and um it returns seven what does that represent that re represents the day of the week so in in this case monday would equal one and sunday would equal seven which seems a little backwards to me but hey that's what you get when you create a language and you set null equal object and other kind of quirks like that moving on console 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 [Music] all in one shot you can get the month today hours minutes seconds and milliseconds um and then there are also some additional date functions for things like conversion to utc or universal time code 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 to at least they've been useful to me in the past but 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 all right 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 some different ones here two are 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 um you realize that uh 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 well you certainly can so let's see this message in all of his glory because i do in fact whoa it's called strings i do in fact love you all right let's move on all right so let's um let's use a couple of uh interesting interesting methods of string so we're going to use the split method i'm just going to call set my split 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 my split and here we have an array with each value as a separate member of our 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 string like format you can split it out all right next up we can slice a string so let's go let my slice equal first dot 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 my slice 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 out power same basic idea [Music] with the next one which is substring it's just a tiny bit different so let my substitute equals first dot 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 five positions so this is the start and then this is the length that we want to pull from that from that first string it's gonna go console.log my substitute and we get that 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 my ends with equals and 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 my ends with true great and um hey well and we can do sort of the same thing let my starts with equal second dot starts with 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 all right so that's true as well and then we can even say hey you know someplace in the string [Music] does it include the sub string or the string there so is the word there used in that second string console.log whoops my include whoops there is no there all right how about capital t in there ah that's true all right so it is case sensitive all right so let's come in all these out which is interesting now let's uh say let my repeat equals ha exclamation mark space dot 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 will 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 and i'm going to put a 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 uh the first time through i'm just going to say trim.link 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 dot 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 dot trim dot 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 the 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 seven characters that means the word bloated should only be seven characters long and it is all right 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 wanted 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 i've 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 all right so we're looking at methods that can be applied to arrays right so um 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 loss numbers and i'm going to concat them to the fibonacci numbers giving me a combined set of array values and here i'm going to go node array dash 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 or i mean push uh elements of one array into the other array that might be a little bit uh a little bit of a cumbersome process you can also do something interesting like console.log and we can take combined or the combine well 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 utility yet and i think now we've used every character on the keyboard at least once all right so let's uh save that and then run it all right 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 tilde now okay we've already talked 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 re 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 great 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 gonna say hey let's add a we can add one we can add two we can add a bunch of items right and so now we do console.log loss numbers oops we'll see whoops what had 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 comment all these out moving on let's um let's find an element uh well first of all here uh 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 all right furthermore what we can do is go console.log names.soar it's a sort of method i got to use the method invocation operator so now when i run it we get the alphabetical order alex david eddie michael all right next up let's um 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 going to go console.log and we'll go others dot index of and i'm going to look up the element name mark all right and so let's see where it's at it should be the third element of the array so i'm going to go back up here to others 0 1 2 3. it's at the third element so then i can go grab it okay 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 one 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 going to 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 ah because i commented it out now let's try it there we go all right so you can see that our combined variable holds 48 15 16 23 42 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 zero one two three four five six seven zero based so the last index of one would be at seven 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.which would give me the first index okay all right moving on you know 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 com 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 all right 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 of that combine array pretty cool and a good example of why you would 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 uh element of an array and inside of that i can then create an arrow function similar to things we've done in the past all right 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 uh 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 um and here's where i'm going to create an arrow function so let's call this num or every one of those numbers less than 10. true or false false why is that well i happen to know that there's a at least a 15 in there maybe if we increase the number to something like 16 are all the numbers less than 16 well they better be because they wouldn't have matched this criteria right true okay so that's the every method of an array similarly we can look at sum so tell me if at least one element of the array matches a condition so here again console.log start with that let's create arrow function um so whoops we'll start off with uh let's use the fibonacci numbers so sum true or false well let's start off here with an arrow function number are all the nums greater than 50. true or false true okay are they all greater than 100 are there any of them it 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 all right 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's 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 uh as a positive thing but personally i wish that javascript's 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 let me paste in a little code i mean this makes absolutely no sense here we're going to attempt to multiply seven times undefined divided by panama okay what's the answer to that well um you know it it looks at and says well i 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 uh 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 a 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 all right 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 to be assigned to the variable a oh 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 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 uh 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 json 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 so an exception in an era i use those terms kind of interchangeably in my mind they're the same thing but whenever a a problem arises an exception is raised by uh by javascript in some way the information about that exception is boxed into one of these um 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 uh 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 in javascript 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 not attempt to catch any issues that might be uh 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 uh 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 yule because uh javascript and in this case visual studio code doesn't recognize it as an apostrophe it recognizes 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 any rate just an aside there line 7 should never get executed because i uh am expecting line number six to essentially throw an exception so um 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 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 um i'm going to go ahead and just hit uh 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 on 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 and 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 all right i caught an exception cannot read b property b 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 all right 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 all right and so you can see that we have we have hit the catch but then it also executed the finally statement before continuing on with the remainder of the application so uh 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 okay so this time let's go function perform calculation and this calculation will take and look at uh a object that will pass in and we're going to say hey if that object obj dot 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 if not has own property equal true essentially then what we can do is actually throw a new error all right so here we'll just describe or give it the message we want to to tell what the problem is object missing property right 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 uh i might just return you know the value six or something like that okay whatever the the calculation using obj dot property b all right so here we go now we're going to call into that function perform higher level function operation and here let's um do let object let that value equals zero all right um and then um 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 [Music] print that out and what i can do then is kind of to show how this would work is uh if um you know value is uh equal to zero 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 to make my application uh 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 let's try that all right i think in this case i'm going to need to do this let's see if that works all right try that again all right 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 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 final 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 gonna have to write some logic to figure out what to do next all right 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 uh then you can ultimately wrap your code in um a try catch statement try catch finally whatever works for you and furthermore you can throw custom errors 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 all right that's all we really wanted to say all right 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 uh 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 unadulterated 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 worked for you and even if this isn't how you wanted to learn javascript i hope you can understand understand and see the the rationale behind it all right 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 and to 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 to see it's it's really quite amazing so let's start at the very beginning i don't want to talk about all the process of 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 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 um and this isn't really intended to be deeply technical uh i'm really just going to paraphrase that 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 uh 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 of that 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 vice probably more likely vice versa a div tag has has a paragraph a div tag has a header has an unordered list which has list items and so on all right so there's that just that nature of html and the the the object model that's being constructed in memory has to consider all those kinds of relationships as well as the attributes and 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 uh 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 all right so that it can essentially at some point visually render those onto 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 uh 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 the functionality that it provides to us like the ability to manipulate uh things like the history the the console window and and any of the other debugging windows that might be available take all of that into consideration and that is that essence something called the document object model or the dom all right and so we'll talk about the dom uh in the remainder of this video in the next couple of videos but eventually after it's taken 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 uh 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 all right so when we create those associations html uh actually gives us a couple of ways to do the create those associations but we're going to look at some some programmatic only ways to create those associations we'll talk about that in the next video but at any rate uh 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 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 nodejs the environment that we've been using up to this point to execute our various little javascript examples they're completely different they have no relationship to each other all right 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 uh the text and so on all right 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 um the class that is associated with that given node we can remove nodes we can add nodes all that programmatically 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 uh 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 are smiled upon in fact most of them are frowned upon there's one that's that's not so you might see some examples and here we'll just add this to our to our uh existing page here that i just created randomly in dom intro.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 a box an alert box in the browser to just kind of execute one little simple line of code uh so let me see how i'm going to do this let's right click on this and let's build rebuild an explorer and from here i can double click and 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 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 high in the console okay so hopefully that all makes sense now using this technique uh 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 uh 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 any everything above this has been loaded already so we can reference the various uh elements in our html all right or the various nodes in our document object model to say in a more programmer friendly way okay 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 message and here i can just do something like console.log um hi and then [Music] maybe dot dot and then maybe a 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 all right 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 will should display in the console log let's open up our web browser again let's refresh this page f5 i'm going to 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 but never really got a chance to and this applies whenever we're 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'll 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 when we by the time we get to the click event handler for this button javascript's already very aware that this function exists all right 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 it might be more appropriate to keep it in its own file and to kind of remove all of these references like this like we have there so i'm going to say don't write javascript in your html page all right and some people might argue with that 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 dom intro.js right and then what we're going to do is actually wire up the event handler to um 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 um remember how to do that we're going to create a function i'm going to wrap it in a parentheses and then we're going to say execute immediately all right and in here what we'll do is we'll define our function or the click handler and then i'm also going to let's go here to our dom intro.html i'm going to give this guy an id and i'm going to say your id is my button all right in fact i hope you don't mind that i'm going to delete all of this out of here all right i'm going to delete all of this out of here it's gone now and i'm going to go into the dom intro.js and the first thing i need to do is get a reference to my button all right 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 butt 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 um hi from my iffy right now i need to go back to the dom intro.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 dom intro dot js so save that and now hopefully let's 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 all right 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 all right all right 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 um hi from iffy all right 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 git element i by id passing in the id and now getting a programmatic reference which we can then use to add or even remove event handlers too in this case i'm just adding a function expression to make it call into another function that i created earlier all right hopefully all that makes sense and we can continue on uh in the next lesson and kind of expand on this all right we'll see you 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 node css and dom nodes js and you can see here that i basically created just a little playground it does nothing of practical values completely contrived but it will show you how we can manipulate various dom nodes and their attributes uh 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 uh a series of div tags each with a color and the name of the 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's 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're 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 uh relative ms rems in css using it the number of times i've clicked it that's the number of rams that i'm applying to this font and so you can see that things are changing they're very dynamic and uh i just wanted to kind of it's a 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 uh though 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 div will contain a series of child divs and i'll talk about more about that more in just a moment and then the resultive is where we add the current number of clicks that continues to grow and grow here we have our script reference to dom nodes.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 uh 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 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 method that we looked at at the very top and then the update ui method that we looked at it was right below it and we'll go and 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 uh in order it 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 uh into our html by the web browser okay so uh 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 all right 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 grabbed these from a website that has colors i think you see the colors i'll give you the site in dom nodes.css all right the first thing we want to do is grab the resultive 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 the incremented click number but then we will also change its size and its color attributes as well all right next up what we want to do is then set the inner text attribute or property of the result object so this resulted we're going to set a property called intertext that's how we're able to put one two three four inside of that div tag here at the very bottom of our white section of our web page okay 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 all right 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 on the keyboard to look at the intellisense 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 uh 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 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 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 all right and so we would use that so that's how i'm using and being able to 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 of what a four so it would be the um we would grab the fourth element from 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 all right moving on now what we want to do is clear out all the existing 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 the bottom border but then also use that color 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 div 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 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 can see i actually append that child append that node that i've been styling up to the larger outermost color div so i do that six times 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 could 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 all right 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 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 ah any uh dom node we can modify it we can add new child nodes to it um creating them essentially out of thin air and we could 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 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 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 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 to build this example and it started really simply it started by can i just increment uh the current number of clicks all right 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 the whole application and that's how i built this all right so um 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 all right so uh let's continue on i guess we're pretty much done so let's wrap it up in the next video see you 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 a new skill 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 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 record it uh to uh to get started with something like vue.js vue.js or react.js by uh by facebook if you're going into a corporate uh software development environment like in a big company then you may want to look at angularjs or angular i think the current version as i record this is version 5. 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 learn 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 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 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 okay makes it easy for you to build entire websites just on the server side okay so um quickly just want to give another plug to my own website here let me type it in for you developer university at devview.com www.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 and 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
Info
Channel: Nerd's lesson
Views: 69,300
Rating: undefined out of 5
Keywords: javascript tutorial, javascript tutorial for beginners, javascript crash course, javascript basics, javascript full course, javascript for beginners, javascript beginner project, javascript basics for beginners, javascript bootcamp, javascript course, javascript coding, javascript class, javascript crash course for beginners, js tutorial, javascript, javascript tutorials, javascript beginners, java script tutorial, javascript 2021, javascript lesson, web development
Id: PXvI0ln6Nws
Channel Id: undefined
Length: 416min 8sec (24968 seconds)
Published: Thu Mar 04 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.