JavaScript for Beginners Course (2020) - Colt Steele

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone it's Colts welcome to my JavaScript for beginners course free course on YouTube it's pretty long video honestly I was hoping to make a nice learn JavaScript in one hour or learned JavaScript in 30 minutes video to keep up with all my click Beatty competitors on YouTube but those are all lies this video would be a lie if I told you you would learn JavaScript in two or two-and-a-half hours that would be a lie as well what I am going to do is give you a solid foundation in JavaScript we're going to cover all of the basics that you have to know the essentials so that you can move on and ends full levon javascript eventually but you know I have JavaScript courses that are 35 40 hours of just JavaScript so saying learn JavaScript in one hour or two is just completely disingenuous but it probably gets a lot of quick so you know probably worth it for them alright so before we get started first of all if you are new here please consider subscribing take a look at some of my previous videos also if you are looking to change careers or become a software engineer take a look at my online job guaranteed software engineering bootcamp it's very low risk if you don't get a job at the end you don't pay anything you get your money back it's something I'm really really excited about spend a ton of time working on this amazing curriculum tons of projects you're paired with your own one-on-one mentor I'll actually be posting an interview I recorded with one of our mentors who works at Amazon it's just one of the many mentors that you could have personally answering your questions if you enroll anyway take a look if you're interested in changing careers there's also a prep course if you're not quite ready to apply so no pressure there now let's move on with JavaScript I'm not gonna spend any time talking about why you should learn JavaScript you know why people are excited about it there are many great videos on that topic I just want to focus on JavaScript and actually learning the syntax so let's go alright so the first thing we need to talk about here are the basic primitive types in JavaScript these are the sort of the smallest things to Adams of JavaScript that everything else is made up of so we have number string boolean null and undefined there are technically two others we don't need to care about them at all and most people don't worry about them symbol and big int so if you think about these different datatypes they're used all over the place there are different types of information and we need to store or represent not just in JavaScript but that's what we're talking about here so we've got a little form and if you were to imagine trying to store the underlying information that a user enters we would need a couple different types of data we have a number here a number of stars from one to five we have some text information we have some more text a name and email and then we have a check mark a yes-or-no a boolean value so just a couple of examples number some text and a boolean so the way that I'll be running code at the beginning here is just using the chrome developer console if you're not using Chrome I recommend you use it although you can you can use the developer console in Safari or Firefox but I would recommend chrome you can also run the code and a whole bunch of other ways but I'm just gonna go with Chrome for now just to keep things simple so I've got a new Chrome window open here and to open up the console there's a couple different ways I usually use the shortcut on a Mac its command option J that takes me to the console and I can start typing JavaScript in this case an error I hit enter and I see the results another option is to go to view developer JavaScript console and if you're on a different machine a non Mac machine you'll see the the shortcut there it's probably what control option J I don't know it's been a while since I used a PC anyway another option that some people like is to go to inspect if you right-click inspect and then go to the console tab there is where we can type some JavaScript so we can make this larger that way or I can pop this out into its own thing which is what I'm gonna do I've because we don't really care about anything else right now so the first type we'll take a look at is number it's pretty self-explanatory numbers and JavaScript are numbers there's only one number type other languages if you have any experience with them often we'll have at least two different numeric types one for a floating-point number of something with a decimal versus integers which are whole numbers in JavaScript there's just one number type it stores negative numbers whole numbers integers or decimal numbers they're all treated the same you can see some examples over here on the left you could just type a number if you wanted to into the console and JavaScript tells you that's okay compared to something like this where we get an error it's completely invalid so we've got numbers negative numbers fractional numbers or floating point decimal numbers obviously there well I shouldn't say obviously if you're new to programming there is a limit on precision so if we have a whole bunch of numbers here you can see at some point javascript is unable to continue storing every single number same thing with a very large number at some point it starts to lose accuracy let's put it that way simply typing numbers into a console and getting them repeated back to you it's not that useful fortunately we do have some simple mathematic operations that we can do things like addition and subtraction multiplication and division just regular old math nothing crazy so we can do things like 45 plus 9 yet 54 9 times 9 gives us 81 7 - I don't know 30 whoops syntax error there can't have that period 7 minus 30 gives us negative 23 we also have some operations that you may not be as familiar with including modulo also known as the remainder operator it's really not that important right now but I hate when people say that in programming videos it's just not that important to be honest anyway it works by dividing this number by the second number so how many times is 2 going to 27 we don't care what we care about is the remainder there is one left over so how many times does 2 go in evenly what is that it goes in 20 13 times and then there's a remainder of 1 26 27 there's a remainder of 1 this is sometimes used or pretty frequently used to calculate if a number's even or odd if you have some mystery number let's just say it's 7 it's not a mystery anymore and if we modulo by 2 mod by 2 if we get 1 as our answer we know a number is odd and if we get 0 we know that it's even so if I at eight or 90 or 100 those are all even numbers two goes in to whatever this number is with a remainder of zero it goes in evenly versus 103 there's a remainder of 1 so that's modulo and one other operation I'll show you that I didn't put on this slide is the exponent exponentiation where I can do something like 2 to the second power to get 4 or 2 to the fifth power to get 32 it's just you know 2 times 2 times 2 times 2 and so on so that is sometimes useful if you want to square something you could do that although it's probably easier just to do 9 times 9 but if you want to cube something you can raise it to the third power so it's 2 stars next to each other and you can also see in these slides I have comments comments are created with two forward slashes and a comment is just a way of writing a note writing some code that won't actually be evaluated s code so you can write you know English or whatever language notes here reminders you can put whatever you want in there and it won't be treated as actual code so I can type something in there that normally would give me an error and it's completely ignored typically though you wouldn't do this in the console you would be doing this in a real JavaScript file with a whole bunch of code where you want to give yourself some notes or some help for your future self down the line while we're on the topic of numbers there is a special numeric value in JavaScript called n a n or not a number or nan nan I just say not a number and it is a numeric value so it's treated as a number but it represents something that is not a number or cannot be represented as a number in JavaScript so the way that we one of the ways we arrive at not a number is dividing something by zero so zero divided by zero or trying to do math with not a number will also give us not a number there's a it's kind of an interesting topic but weird we don't have time to go into it and it's really just something that you'll run into occasionally if you're doing something wonky with math 0/0 gives us not a number once we talk about strings if you're trying to write a string by a number some text by some number JavaScript doesn't know what to do with that so it tells you the answers not a number there's also infinity and negative infinity 2 divided by 0 gives me infinity negative 2 divided by 0 gives me negative infinity not that common to work with them but you should know they exist so now let's do a quick little quiz this one hopefully is simple enough what does this evaluate to nothing crazy here hopefully really just testing math so this is going to be 1.5 times 2 that will run first because of the order of operations which javascript respects or obeys so that gives us 3 plus 1.5 that should be 4.5 here's one more what does this give us all right and here's the answer we have on the left hand side in parentheses 10 mod 6 what we just learned about modulo it's the remainder operator how many times does 6 go into 10 one time what is the remainder 4 so the answer here is 4 on the left side and then we are star starring it that is the exponentiation operator so we're raising 4 to the 2nd power which is going to be 4 times 4 which is what are you 16 so I think that's the answer and indeed it is ok so while we can use JavaScript as a glorified calculator to add and divide and all of that there's obviously a lot more that we can do and the first new concepts will introduce our variables so variables like pretty much everything we're going to cover in this video are not specific to JavaScript if you're new to programming things like variables exist across pretty much every language out there so a variable is a way to store a value and give it a name you can see on this little slide here I like to imagine it as a jar that has a label on it and then some thing in that jar some value so in this case we have a variable called age set to the number 72 so we could recall this value at any point I could say JavaScript would this value of age or I would like to add one to the value of age because it's a birthday or my birthday today there's a lot that we can do with variables and they're essential to really building anything useful so the actual syntax to right or to create a variable looks like this let that's a keyword there so it's always let and then some variable name equal sign and then some value so here it's very simple example let age equals 55 Java scripts please make me a variable called age give it the value of 55 here's another example I'm making two variables hens and roosters notice the semicolons there that's a larger topic in JavaScript as to whether you need them or not or when you need them or not all that I'll say about it for now is that JavaScript will actually automatically insert semicolons behind the scenes if you are lazy and you don't put them after a line but in the case of variable declarations what we have here we should add a semicolon it's just better to be explicit so let hens equals four that's the number of hens I guess let roosters equals two and then at any point I can recall hens or roosters or both of them together I can sum them and I would get six so it's just a label for some value so let's try making our own here in the console let's create a variable to store I don't know if the age of my dog and we need to start with let's typically in JavaScript are conventionally in JavaScript we go with a camel case variable name so that would mean something like a dog age so we have age a and age is uppercase but everything else is lowercase or I don't know num of chickens it really doesn't matter to the language but you won't really see anything other than this camel case except for the very first letter is lowercase anyway let's go with dog years or dog age and we'll set that to be eight years old so I have a dog that is eight years old and I hit enter now I can ask for dog age at any points and JavaScript tells me I know that it's eight if I misspelled it or capitalize it incorrectly I will get an error dog age is not defined so capitalization definitely matters as those spelling now if I did something like dog age times I think I mean this is probably all BS but growing up I was told it was seven years I think to go from one dog ear to a human year so multiply by seven this dog is allegedly the equivalent of 56 human years old now what is the value of dog age after this I have not changed it at all all that I've done is asked for the value and multiplied it by seven but that value is still the same in memory now I could save a new variable like I could do something like let's new age equals and then dog age times 7 and now I have a variable new age that has 56 in it I could also do things like take dog age and let's say my dog had a birthday I could say dog age now equals the current dog age plus 1 and now I'm saying whatever the current ages which is what is it 8 add 1 to that so that's 9 and set that to be dog age and there's actually a shortcut syntax to do things like this I can say dog age plus equals 1 or plus equals 5 this is the same as saying dog age equals the current dog age plus 5 so if I did this the new value for dog age would be 14 and you can see that here it's stored as 14 there are a whole bunch of other variants I can do things like star equals 2 and that is going to be the same as dog age equals dog age times 2 so now it's 28 ok so that is one way of making a variable in JavaScript the let keyword we also have another keyword called Const which stands for constant it's basically the same pattern that we follow let hens equals 4 versus Const ends equals 4 but the major difference here is that with a constant variable declared with a Const keyword that value cannot be changed it is set in stone it is a constant so I can do something like Const age equals 17 but I cannot reset age to be some new number there are some other distinctions not going to go into it here I have like a 10 or 15 minute video just talking about let versus Const I'm going to clear the console just command K here probably control K if you're on a PC or Windows machine I'm not sure if I make a variable with Const how about well I guess I should show this if I trying to do Kant's dog age and set that equal to something it's going to complain to me that's we've already created a variable called dog age so it's important to understand that we can't have variables creative with letting Const using the exact same identifier the same name so why don't we do something else how about Const I don't know here equals 20/20 okay so I made a variable with Const it works the same way or it seems to work the same way but if I try and change year year plus equals one I get an error I cannot assign to a constant variable but if I had used lots that is not a problem so it seems like Const is read limited in its utility but that's actually not the case later on you'll see that you use Const frequently with things like arrays and objects so I think we have not covered yet also if you had some value that you know should not change the number of days in a week the value of pi' minimum height for some rides 60 inches if these values aren't supposed to change then you can use constant to declare them also there's an older way of declaring a variable previously in JavaScript we only had one option which is the VAR keyword var same pattern s let and Const but these days because lettin Const are sort of a newer and better versions of var almost nobody years as far I I can't think of a good reason you should use var but you should know it exists if you see old tutorials or videos you may see var used but letting Const are replacements and again there are some important distinctions as to why Lutton Const were proposed and added into JavaScript over var but we're not going to get into that here so quick quiz what is the value of the egg count variable here after the second line of code runs and the answer is it does not change it starts as 42 and then we retrieve the value and add two but we're not adding two to the variable itself so the second line is going to tell us 44 it's going to give us the number 44 but egg count is unchanged and here's one more what is the value of rating after this line of code runs consecrating is 7.5 rating equals 8 can't do that it's declared with Const that is a big no-no and javascript is going to yell at you so the value of rating is unchanged it stays 7.5 alright so returning to this slide here with the different primitive types so far we've only covered numbered now we're going to talk about some of these other types first of all a nice and easy one boolean s-- boolean values are very simple there are only two possible options true or false they are just a black or white yes or no 1 or 0 value that is it there is no nuance there it's either yes or no true or false and specifically we spelled true or false this way all lowercase some other languages will have an uppercase T for a boolean value true or an uppercase F but in JavaScript true and false are very special keywords they are boolean values so we can create a variable and store a boolean in there is logged in equals true game over equals false is water wet equals true it's relatively simple especially compared to numbers but if we just create a quick variable here at boolean how about let's is purple great color that is true purple is a great color there we go true so if I type the word true in JavaScript I don't get an error but if I spelled it with a capital T we do get an error JavaScript does not know what I'm talking about but true and false all lowercase are important boolean values also you should know that variables can change type in some languages this is not really an option but in JavaScript it is so if I'm storing something like is purple great color and it's set to the value true the boolean value for some reason if I wanted to I could set it to be the number 7 that is not a problem in JavaScript it is a problem I guess logically it makes no sense whatsoever to have is purple great color set to 7 but we can in JavaScript moving on to our next data type a really important one the string so strings are pieces of text strings of characters and we always wrap them in quotation marks now these can be single quotes or double quotes but you need to make sure that you whatever you start with if it's a double quote you end with that if it's a single quote you end with a single quote if you mix them up you will have a bad time so you just need to be consistent and let me just show you a couple of quick examples here I could make I don't know a variable called first name I'll use Const and set it equal to how about Thomas I can use single quotes and there we go I now have first name set to Thomas again the quotation marks don't actually matter you just need to be consistent I'll do another variable this time with let's let's do let color equals and I'll do double quotes purple notice I forgot the semicolon that was unintentional but it doesn't actually matter JavaScript well and the console it's extra easy it doesn't really matter but anyway there should have been one there to be super precise color is now set to purple okay we could also have spaces and how about let phrase equals the early bird gets the worm [Music] that's also a string now there is more there's quite a bit that we could talk about with strings I'm just going to give you a crash course in them let me just show you what happens if you tried to do something like let message with a single quote and then a double quotes we get a syntax error it is not happy with us strings are an indexed type in JavaScript which means that every character in a string has a corresponding index basically a positional number a number that corresponds to a position in the string and those numbers start at zero so as you can see in this string chicken C has an index of zero K has an index of four they all go in a row it's just a way of referencing each character and I can access one character at a time if I want to using square brackets and then some index inside those brackets so if I wanted to know how about our color variable right there if I wanted to know the very first letter of color I could ask for color of zero and get the character P I'm not changing the string in any way I'm just accessing one tiny character the first character I could also access the second character with index of one that's all I'll show about that for now also strings have a length property so every string we haven't talked about the term property but every string has this thing called length we access it using dots and then length and you can see that length is set to six there are six characters one two three four five six if I look at my phrase variable let me clear this phrase dot length gives me 28 also this is an accidental space but JavaScript ignored it here I would definitely not put a space there on purpose so 28 characters in that string now if we go back to color and we look at the length it's 6 if I can type that correctly but that does not mean that there is a character at the index of 6 I get this other value we have not yet covered called undefined there is nothing there because our indexes or indices start at 0 they go from 0 up until 5 in this case so the last character in color this e has an index of 5 right I could access it with color square bracket 5 okay so every string that we make in JavaScript comes with a set of built-in methods methods are basically actions that can be performed on or using some particular string so these include things like searching within a string or changing the casing upper or lower case replacing parts of a string repeating a string there are many different things we can do I'll just show you a couple but the syntax for all of them is very very similar we have some string or some thing dot and then the name of a method and then opening and closing parentheses so for example there are two built-in methods that every string has access to called two uppercase and two lowercase these have to do with changing the capitalization of a string so over here I have a new variable called message msg it's set to get out of my room mom and it's all in lowercase it's not a comma in there now if I called message dots to uppercase and this also has to be capitalized correctly it's not to uppercase with the lowercase u it's all let's not all uppercase its camel cased and if I just hit enter now I'm not gonna really get any results because I'm not executing the code remember what we talked about we need those parentheses so here JavaScript tells me yes I know about that thing to uppercase but it's not actually executing it I need to add those parentheses in order to run that method and this is what we get back get out of my room mom in all caps now it's also important to understand that message is completely unchanged this method is going to take the value of that string and make a copy of it that is all uppercase but it does not update the value of message itself now I could do that I could do message equals message dot to uppercase or I might do something like let yell equals message to uppercase and if we look at yell it now says get out of my room mom and all caps but message is unchanged so we also have to lowercase so I could do yell dot to lowercase by the way in in the chrome console and in most editors if you hit tab for autocomplete it makes things a lot quicker yelled to lowercase get out of my room mom we're back to lowercase okay so there are many other string methods if I just type some string here how about lol lol and then I add a bunch of space you'll see why in just a moment and then I type a period to trigger Chrome's autocomplete of methods all of these methods that we call start with period her they don't really start with period but we use the period a dots then the name of the method to access a method on a particular string so when I type a period here I can see we have methods like to uppercase and to lowercase that we just talked about but we also have things like one called trim which I don't really use very often but if I add those parentheses you'll see that it trims off the space at the beginning and end of the string but it does not change any internal spacing so this can be used sometimes to clean up an input something coming from I don't know a forum or something where users are inputting in from and they might have additional spaces on either end anyway there's a lot of string methods it's not essential enough for us to spend a lot of time on them but what I do want to talk about here is this pattern where we have some thing so far just strings and then a method name and then parentheses and then something inside the parentheses something we call arguments so arguments are pieces of data that we can pass to a method to modify the behavior or just to provide some information to that method so we pass them inside of parentheses and a lot of the built-in string methods accept arguments for example there's one called index of which will tell us the index of some string within another string if it exists so in this case I have a string TV show and it's set to cat dog and then I'm calling index of on TV show and I pass in cat CA T I'm asking where does this particular thing this argument where does it occur in TV show and the answer I get is index of zero it starts right there index of zero at that see if I did dog we get index of three zero one two three and if something is not found in a string then we get negative one so I'm not showing this right now because you'll need to know index of although it's good to know I'm showing it more to illustrate this concept of arguments of passing in some values to a method so here's another example this is called slice there's more to slice because we can actually pass in more than one argument what slice will do is basically make a copy of a portion of a string so here I've got this very long string supercalifragilisticexpialidocious sets the variable named str1 I call slice on it STR slice I can pass in one number like I'm doing on the bottom here and if I only pass in one number it is going to make a slice of a string starting at that index so if I have something simple how about ABCD efg dot slice and then I pass in an index here like three you can see even before I hit enter what I'm getting d e f G so if we count the index indices indexes indices 0 1 two three it goes from three to the end of the string but if I pass in more than one number for example 3 comma 5 I'm going from index of 3 up until index of 5 de if I did 3 to 6 de F so I'm making a new string I'm not manipulating or changing the original string so if I had a variable like what phrase equals I already have that let's see the early bird gets the worm and then I call phrase dot slice how about I don't know index of 10 to the end bird gets the worm that is what I want to slice I am not changing phrase in any way like we've seen with to upper case and to lower case I'm simply making a new string based off of that one but I could capture that into a variable I can recall that line with the up arrow in chrome and then I could save that into a variable let new phrase equals phrase dot slice and now I have new phrase and phrase all right so those are two examples of string methods that accept arguments here's one more this is replace where we can pass in some string that we're trying to replace within a string so I'm trying to replace t he within t he's so funny T he and I want to replace it with haha so it will replace it if it finds T he only the first time so it's not going to replace this t he over here another example I'll show you is repeat I could have the string ha dot repeats and I can pass in a number in this number this argument here specifies how many times this string should be repeated all right so methods very important strings have lots of built-in methods and this actually brings up an important point here which is how do you find these methods and how would you know what these methods are well the place that I like to go to is a website called mdn Mozilla developer Network it provides some great documentation for things like HTML CSS JavaScript and I'll show you the home page here developer mozilla.org I usually just type mdn into Google and there's a lot of stuff here but if you go to references and guides there are some tutorials if we go to technologies go to Java scripts there are more tutorials but then mostly what I'm really focused on are the standard objects specifically what we're talking about right now string but if we were talking about number like we did earlier you can read more about number here or I've boolean you can learn more there but let's look at string on the left hand side here we're going to see a bunch of different methods these are methods that we have on every single string although some of them have a little down what do you call that a thumbs down this indicates that you shouldn't use them anymore they're basically deprecated they're not encouraged and not all browsers support them but even if we ignore those there are quite a few different methods and we only covered two or three or maybe like five of them if you wanted to learn more about them pick one let's go with how about starts with and then we have an example of how it works we have an explanation it determines whether a string begins with the characters of a specified string returning true or false as appropriate anyway I'm not really here to show you every single possible method but this is where you can learn more about them you definitely do not need to memorize them at this point quick quiz here what would you see if you ran this code in your chrome console what is the output well we're asking for index of seven zero one two three four five six seven we would get I as you can see there all right one more what's the answer here index of three of pup PU P well three letters they're three characters but there's no index of three the highest index is two zero one two so index of 3 gives us undefined PU P of three undefined all right quick quiz again what is the value of song after both of these lines have run so I'll give you a moment or you really should just pause it I guess I'm trying to make this brief the value of song is unchanged song begins as London Calling in lowercase and then we call song two for case but it doesn't change song it's just making an uppercase version but we're not storing it in a variable we're just yelling its or whispering it no I guess we're yelling if it's to uppercase we're yelling it into the ether but we're never capturing that uppercase value so the next important topic around strings are something called string template literals and these are actually a newer feature in JavaScript they've not been around for very long and we are very happy that they are around they make our life a lot easier so template literals are special strings that allow for embedded expressions basically we can add variables or I mean math if you wanted to any sort of expression that will be evaluated as JavaScript and then turned into a resulting string so here here's a simple example I counted and then there's some special syntax 3 + 4 sheep that will be turned into I counted seven sheep seems silly to just write three plus four when we know ahead of time we could just write seven but this is very useful when we have some piece of code some variable a user's name or a number of emails in an inbox we don't know ahead of time but we want to make some string based off of now syntax wise we use backtick characters not single quotes so it might look like single quotes but those are knots they are back ticks we can usually find the back tick key above your tab with a Tildy character they share a key at least on my keyboard and you need to use them to indicate that you are writing a template literal so if I just use a back tick and I write some string hello it's turned into a regular old string there's no reason really to do this but we can it's another way of declaring a string but what's fancy and special is that if we add a dollar sign and then curly braces inside of a string only a string declared with those back ticks so back take back tick and then dollar sign curly sign tell their sign curly sign dollar sign curly braces whatever code I put inside of here I could do math I could do something else usually not math but whatever I put in there is going to be a value and turned into a string so if I leave off that dollar sign I leave off the curly braces we just see exactly what we've typed as a string but if I put dollar sign curly braces that code is now treated as JavaScript to be evaluated as if it's not in a string and then it's added in so I can do things like your total is and then actually add in a total a very weird total I don't know why you're dividing by 23 but you get the general idea so I could have some variable like a username but username equals Batman 87 sure and then I could make some new variable how about a greeting variable and set it equal to a string template literal welcome back comma and then I can put the username right there again very useful not in the console like we're doing here sort of a distiller sandboxed very beginner environment but in the real world you have a lot of information that is dynamic that comes from a variable might be coming from a database or somewhere else and you want to do something with it inside of a string string template literals make it very easy so now if I look at greeting we see welcome back Batman 87 so remember you've got to use those back ticks not single quotes not double quotes but only back ticks with dollar sign curly braces will allow you to embed expressions in a string all right so back to this slide of the basic primitive types we've covered three out of five the last two Nolan undefined are much shorter so I put both of them on the same slide I'm talking about them together because for a lot of beginners they can be a little bit confusing they seem similar but they are definitely distinct concepts so null is a particular type it's a value in JavaScript that is the intentional absence of a value and it must be assigned for example we could have a variable called logged in user and if no one is logged in at the beginning we could set it to null instead of setting it to zero or I don't know an empty string or something which doesn't necessarily make sense we can set it to be explicitly nothing it just is a you know Liz a value that represents nothing there is an absence of a value there then we have undefined undefined is a bit different we're not going to assign something to be undefined at least not usually instead variables that don't have an assigned value will be undefined for example if I make a variable color but I don't give it a value totally valid but at the moment there's no value in there so its value is undefined then I can set it to something else how about I don't know electric blue and then we look at color it's obviously not undefined anymore or another example we've already seen this as well as if I did color and then some very high index that we know does not exist we get undefined that value is not defined versus I could set color to be explicitly no which I guess would mean there's no color at all something is colorless and is a value that we deliberately use we set something to know undefined is something that typically we get back from JavaScript it's not something that we set on our own alright so that about wraps it up for primitives and variables of course there's a lot more that we could talk about and yeah I have courses where we do talk a lot more about those topics but those are the essentials that's really the core stuff you need to know on primitives next up we're going to start talking about making decisions in our code how do we have different outcomes and the first thing we need to cover our comparison operators javascript comes with a couple of more than a couple seven eight and I can't count very quickly a bunch of different comparison operators which allow us to compare one value to a second value and they all return either true or false a boolean value that's it there's no in between there's no gray area it's either true or false so you're probably familiar with some of them greater than unless then I could just show you that very quickly here it's easiest if we're working with numbers so 3 less than 5 that is true so we get true the boolean value true as the results if I instead did 3 less than 1 we get false right and then we have greater than is 3 greater than 0 three greater than negative one yes we also have greater than and equal or greater than or equal rather than less than or equal to so we could do things like is three greater than or equal to four that's false - that's true 3 is greater than 2 and 3 is now true as well 3 is greater than or equal to 3 but if I did 3 greater than 3 we get false and we also have less than or equal to and before we go on to the bottom 4 which have to do with equality or non equality I want to talk a little bit more about comparisons and using less than greater than so far we've been doing it with numbers which is definitely the most common though you can compare other types you could compare strings to one another just beware that the behavior may not be what you're expecting the way that it works behind the scenes very briefly is that every character has an underlying unicode value a number that represents or that corresponds to that character so this is just a small subsection but you can see things like upper case a has a 41 or has the number of 41 and a upper case B has 42 simple enough so we could tell that upper case a is going to be less than upper case B 41 verses 42 but what if I did lower case a less than upper case a a lot of people think that lower case would come before upper case that's not the case if you look at the chart again you'll see upper case a is 41 lowercase a is somewhere on here have probably already passed it 61 and there are corresponding numbers Unicode numbers for all sorts of characters so not just the what is it the Latin alphabets but also special characters numbers accent marks lots of different marks and identifiers as you can see here from different languages different alphabets they all have an underlying number and that number is used to make the comparison so just keep that in mind it's not very common that you'll need to compare one sentence to another but in JavaScript you can it just may not behave the way you expect okay so now let's talk about equality we did less then and greater than when we're checking to see if values are equal to one another we actually have two different options double equals and triple equals this is a very important concept in JavaScript we'll start with double equals double equals also known as the loose equality operation or operator checks for equality of value but not of type so what this means is that it's going to coerce it's going to try and take the left and the rights and make them the same type a common type and then compare them and this can lead to some unexpected results so things like five equals five or a lowercase a equals lowercase a you can see I accidentally typed triple equals because it's so ingrained in me to use that but if I do double equals it is true if I did one equals one true and at this point you might be wondering why would you do any of this right why would you need to know if one is one well usually we have a variable we would have some variable like let secret password and I'm going to type something in here and then clear my screen and then I could have another variable we'll call this one guess equals and maybe our guests will be monkeys monkey one two three sure okay and then I could compare I could attempt to log in still very simple but is guess equal to secret password nope you got it wrong very simple logic but this is the sort of thing that we'll do all the time or that you'll do all the time in JavaScript or much more complex than this but having some sort of logic typically involving variables values that you don't know ahead of time now if we look at secret password it's close monkeys 1 2 3 uh well I forgot an S but it wouldn't have mattered because lowercase M uppercase M they are not considered the same completely different characters as we saw they have a different underlying unicode value okay so double equals works how you would expect it to work a lot of the time but there are cases like this 8 double equals the string ate one of those is a number another is a string they are not the same yes they might present the same concept of eight but they are different values entirely but using double equals they are coerced into the same type and then compared and we get true now this can be problematic at times and for the most part people will tell you to avoid using double equals just to show you some other examples if you do something like zero double equals false once again completely different they're not the same thing but double equals will tell you that they are now if we use triple equals which is known as the strict equality operator it cares about type not just the Equality of value it's not going to try and coerce the values to be the same type so if we instead did eight triple equals the string eight we get false double equals it's true same thing with the zero double equals false that's true but if I add a third equal sign it is false so the main takeaway here should be always use triple equals maybe there'll be a time down the line if you have a long and storied JavaScript career where it might make sense for you to use double equals but for the most part stay away from it like it's I guess well I was gonna say the plague but I guess it's a bit of a poor taste phrase these days just don't use it and then we also have non equality it's an operation or a comparison that we can check to see if something is not equal to something else so I'm going to clear this here I could check if one is not equal to one and that gives us false because they are equal so if I did 1 is not equal to 2 now we get true now this version here with a single equal sign is going to coerce types it's like double equals so if I did 1 I don't know not equal to 1 the string I get false because it tries to coerce them to the same type it compares them and it realizes hey wait a minute they are the same even though they're not the same but if I did double not equals we get true so I pretty much always use this one as well it's it's stricter just like using triple equals so avoid ignore the existence of not equals and double equals do these guys instead as this slide hopefully makes clear go with triple so we're about to start working with files and actually running our code from an external file instead of just one line at a time in a console we needed this to get the basics it's just fast and easy you don't have to download anything you don't have to worry about including scripts and setting up an HTML document all you have to do is write code and the console and hit enter but we're going to move over to files because usually we want to write multiple lines of code we might have hundreds of lines or thousands and we want them to be savable and persist unlike our console which just goes away if I close this window so one thing I want to show you right now while we're here is a particular built in method in JavaScript called console dot log and it's gonna seem kind of useless until we start working in a file console dot log is going to print some values whatever we pass in as arguments it will print them to the console so this seems silly because right now I can print something to the console by just typing one or whatever I want it's printed that's the console if I call console dot log it is a method just like a method we call in a string like to uppercase I need parenthesis if I leave them off nothing will happen I don't run any code but if I add parenthesis and then I add some value in like one it prints it out for me now it is a little bit different what we're seeing here without going to too much detail if I just typed the number one and hit enter this is the return value it's not necessarily printing it yes it is showing up visibly for us but there is a difference it's something we'll talk about later when we learn about return values and functions but for now it doesn't seem that useful but I'm just going to show you if you pass in multiple values in here it doesn't matter what they are as long as they're valid JavaScript and let's do true as well they will all be printed to our console so when we're working in a file this is really useful especially when you're starting out because it's how we can print code from a file into the console otherwise we don't really have a way of seeing a result or understanding what our code is doing so we need to use console dot log it's equivalent to things like print if you familiar with Python or other languages I wish it was just called print and Java scripts but it's not it's console dialogue it's a method you need parenthesis you pass in your value so you want to be printed okay so next up let's actually run code from a file let's write JavaScript not in the console but in a file and run it now the way that we do this is a little bit clunky err than you might expect if you're brand new to this we don't just make a JavaScript file and click run we actually have to make an HTML file and in that HTML file we include our JavaScript file as a script now if you don't know any HTML it's not a huge deal I do have some intro videos for free on YouTube that go over pretty much all of HTML and CSS but it's not at all necessary for this next step so the first thing we need to do before we write any code is have a place to write the code and the editor that I recommend that I use and a lot of developers use these days is called vs code or visual studio code it's free it's it's really really good lots and lots of amazing features tons of plugins and extensions and a big community around it but you don't have to use it you can use something like TextEdit if you wanted to or notepad Microsoft Word I guess theoretically would work too but usually you'll use something like vs code or sublime text so all you need to do is click download if you don't have it already and then open it up and you'll see something like this and it probably won't bug you about updating like mine does so this is an empty editor we need to make an HTML file as the first thing so I'm going to right click or you can go file new file or just command + new file and I'm gonna name this something dot HTML I'm gonna go with index dot HTML it's a pretty standard name for a HTML file I'll make this a bit larger and because we're not really gonna go over HTML here I'm just going to hit exclamation point tab and that fills out my basic HTML skeleton for me again not the point of this video now I'm going to make a separate JavaScript file and I'll just call this app dot jas you can name it whatever but it needs to have a jas and then in here we'll put a line of code console dot log hello from your file something like that I mean you can just do console dot log 2 or 1 or X it doesn't matter but just something that we'll see in our console and save this file and in our index.html we need to include this script and the way that we do that is by adding a script tag usually I just type script like that and then hit tab and then set a source attribute to the name of our file again if you're brand new to HTML don't worry this is just something you'll do so script and then SRC equals quotation marks and then opt-out j/s assuming that that is the name of our script if you named it something else make sure that name is here already now we need to open this file in our browser and we should take a moment to talk about why we have to even do this your browser is set up to understand HTML files it's not set up to understand JavaScript files on their own so your browser can't understand JavaScript but it needs to be included via an HTML file which is exactly what we're doing so our HTML file doesn't really have anything in it there's not a web page that will be displaying there won't be any content that we see it's simply a vehicle to get our browser to run a script so now we need to open this in our browser there are many ways of doing this the simplest is to double-click on your index.html if you can find it so here's my index.html I'll double click that and you'll see something like this in your browser so not much to look at we don't have any HTML content but our script should be included another way of opening up a file is dragging your HTML file to your browser or going to file open or Open File something like that but I just like to double click the file and now if I open up my console this is what I see hello from your file now I might just collapse this back in Chrome just to go on the side or something like that probably anyway we can tell our script is running because we see hello from your file if you didn't see that and your code definitely includes something like hello from your file or you're just counseled out locking anything it doesn't matter what it is as long as it's valid in JavaScript you want to see that here now if I change my file which I just did I have to save which I did and I have to refresh the page I have to reload and get a new version of that script and half the browser executes it and it prints out one to nine bla bla bla bla bla all right so that's our basic process well write some code in here I can save it I can close down my editor I can come back years later and then open up a file in the browser and hopefully get some results at least in the console for now eventually you'll be writing code that changes something that you see in the browser here maybe makes nice animations maybe implements a board game I don't know live-chat all sorts of different features that are powered by JavaScript written in separate files alright so now let's keep learning more JavaScript we're going to talk about conditional logic this is how we can actually run different code depending on some sort of condition on some logic so the first piece that I'll talk about is the if statement it's I guess relatively similar to English how we would approach some conditional thing in in the real world if you eat all your vegetables you can have dessert I heard that a million times as a kid actually what I usually heard was if you eat all your vegetables and your two sisters eat all their vegetables then you can have dessert it was a horrible tactic my father implemented called team eating anyway long story short same idea here in code if something do this so we have a variable called rating clearly it is hard-coded it is set to 3 but imagine this is coming from a database or a user a form we don't know what rating is and if rating is exactly equal to 3 we will console that log you are a superstar so if and only if rating is 3 so let's try that out with something else how about we make a variable called score like a test score and we'll set it equal to about 91 sure now I'll use the I don't know if it's the American grading system or what grading system it is but letter grades a b c d and then for some reason there's no e and we go right to an F anyway we'll use some of that and basically if if score is greater than 90 we will console that log you got an a on your test or something like that okay so we'll start very simple if and then our parenthesis this is the format we always follow if parenthesis and then some expression that evaluates to true or false a boolean expression typically involving those operations we've already seen or the comparisons we've already seen less than greater than that sort of thing so if score is greater than we could do greater than 89 or how about greater than or equal to 90 and then curly braces and those curly braces are very important whatever code we put inside of them whether it's one line or ten lines will only run if this is true so in here I'll just do a console dot log you get an A and we'll start with that let's go to our browser remember I do need to refresh the page and we see you get an A okay simple enough now what if we change score to be 80 well refresh the page again we don't see anything okay so that is our first very tiny decision tiny little change in our code depending on this one variable that we are hard-coding yes simple nothing crazy but this format is very very important if some expression in parentheses and then curly braces now if I have other code after this something like console dot log you did not get an A this is not exclusive from this both of these could run in fact if this one runs this one will always run afterwards what I'm trying to say that's a bit clunky honestly is that whatever you have after or before this if doesn't really matter it's going to run as long as it's not inside of some sort of conditional block so this might run and then this will definitely run or this might not run and this still run so right now if i refresh the page we get you did not get an a but if I change this back to about a 90 this time we will see you did get an A and you did not get an A so these are not exclusive and that brings us to the next piece all introduced of a conditional statement we have if and we have an else else is basically if this was not true I would like you to do this so if score was not greater than or equal to 90 we will console that log you did not get an A you did not get an A now only one of these will run this one or this one so if this is true we'll console dot log that if it's not if this is false that triggers the else so with an else we don't have parenthesis you don't have an expression in there because it is the last case it is basically if nothing before this was true then run this so there is no expression we pass in but we do have curly braces and then we write as much as we want inside those curly braces and let's just see what happens score is 90 refresh the page we still see you get an A now if score goes to 70 or 80 refresh we see you did not get an A and that's the only thing we see okay so that's else you know we could make a simple coin toss actually why don't we do that for a moment I'm gonna comment this out the easiest way to do that in vs code is to hold or just highlight something and then hold the command slash I believe it's control forward slash on a PC I'm not positive though remember comments are just a way of having our code not run but leaving something there so we could write notes but I'm just gonna comment it out so it doesn't run and what we're going to do is print out heads or tails randomly now we haven't really talked about random numbers so I'll take a moment to show you how you can generate a random number in JavaScript it's kind of annoying there's a method called math dot random and it gives you a random decimal number a random float between 0 & 1 and it's really long and ugly yeah I would wish that there was just an easy way to get a random number like an integer between 1 and 10 or 1 and 2 or whatever it is we can do that but we have to do some additional math but for us if we're gonna make a coin toss we just want two random numbers 1 or 2 or 0 or 1 for heads or tails what we can actually do instead is just pick a random number like this and then check if that random number is greater than 0.5 or less than 0.5 because it's a random number between 0 and 1 so it's simple enough to do we will call math dot random save that to a variable we'll just call this R and num equals math dot random so that will be some random number this math object we haven't talked about objects but this math thing by the way has different methods on it not just random it has methods for what else for rounding numbers or for flooring numbers and truncating them there's a bunch of different math e related methods on this thing called math but we're just gonna use math dot random for now then well write a conditional now go ahead and write this out if you'd like to I would like for you to console dot log heads if let's say if rand num is less than 0.5 otherwise console dot log tails so here's one way of doing it if rand num is less than 0.5 console dot log heads and then else console dot log tails simple enough let's see what happens refresh the page and I get heads the first time then tails heads tails tails tails tails heads and so on all right so another simple enough example of a conditional if and an else but we have a third piece that we'll introduce which is the else if so else if is a way of adding another condition after your initial if so if not the first thing maybe this other thing or maybe this third thing or this force thing and then finally the at the very end will be a catch-all so the syntax is else and then a space if and then our parenthesis and our curly braces let's go back to our original score' example so I'll comment this out maybe I'll add a comment here that just says coin toss example ok and then I'm going to uncomment this you could do it manually by deleting all those slashes or by selecting and then the same shortcut to toggle the comments on also toggles them off command forward slash on a Mac ok so right now it's just if this and then otherwise this but as we know there are many other grades let's just worry about an A and a B so if your score is greater than or equal to 90 you get an A but what if your score is between 80 and 90 it's a a B right so I could add in an else if just like this you don't have to do these on the same line you can do this instead else if and just put each one on its own line so in here else if requires parentheses and some sort of expression else is just the fallback it's the the very last thing if nothing above me matched okay then do this but else if has a condition that's required so else if score is greater than or equal to 80 it will console dot log you get a be very confusing to have a B but you can a B and remember this can only ever run this line right here if this did not run so it's going to go in order and we'll try this first is score greater than or equal to 90 if it is this runs and we're done nothing else runs here nothing else in this conditional block at least now if this is false if score is not greater than or equal to 90 then it will try this score greater than or equal to 80 yes or no well it depends let's say it is will console dot log this if it's not we console dot log this as the fallback so right now score is 80 if i refresh the page you get a B now if I go to a 90 and refresh the page you get an A and if I go to a 70 refresh the page you did not get an A well that's not I mean that's true but it's not very helpful because you also did not get a B so I could flush this out a bit more I can add as many else ifs as I want so this one will be scored greater than or equal to 70 you get a C and then another one if it's greater than 60 you get a D and then else you get an F would it be an NF AF anyway so let's test it out now score will be 70 here refresh you get a C how about score it's now 20 very low score you mess it up that should be you did good yeah but you got an F or you get an F okay try that again you get an F how about 69 you get a D geez it's a little and you end o heavy there apologize it's not intentional about 75 you get a C and we've already seen 85 90 all that stuff so we have some very simple logic just based off of a single score that's hard-coded we have different outcomes we try this first if that is not true we try this if that's not true then how about this one and then this one and then eventually if nothing else was true before run this line or whatever we have in here could be multiple lines now I should have semicolons in there as you've already seen it doesn't really matter at this point it's not breaking anything but it's always good to put them in you do not want semi-colons after curly braces or after a conditional or anything like that the rules I'm not going to go through and explain them all at the moment but I mentioned this earlier that JavaScript will add semicolons in for you where when it thinks you need them sometimes you can get it wrong and cause problems but for the most part it's not a big deal over time you'll learn where they're where they're necessary and when you should add them okay another thing we can do with conditionals is nest them so we can have one if for an Elsa for an else and inside of those curly braces add a new set and if and else if and an else and so on so here's an example it's slightly more complex in what we've seen so far where I'm checking to see if some password variable has a length that is greater than or equal to six if not we're going to console dot log password to shorts but if it does have a length that is long enough for our password then we're going to check if there's a space in there I'm using index of string method we mentioned it briefly it tells us the index where some string occurs in others in another string and if it does not occur we get negative one so this nested if right here is checking to see if there is a space inside of password and if there is we console that logged password cannot include spaces otherwise we console dot log valid password so we have one if and then nested inside a second if let me show you another example over here with this silly little score example console that log you get an a I could add another if inside of here how about if your score is greater than what not what's an A+ it'll be in 9899 let's just say it's a 98 sure so if score is greater than or equal to 98 I don't know why I added that extra space there we don't need it but if it's greater than or equal to 98 we'll consoles out log extra Congrats you get an A+ okay so we have an if inside of an if so this will only run if this part is true and it will only run if this top part is true so there is a world where we could have something like if one equals one that's always true but it's only going to run this code will only be executed if this conditional if this if right here expression is true the code inside those curly braces runs and then this would run so nesting does have it has important consequences it's very different compared to just putting a conditional outside of a parent conditional it's a poor way of saying it but nesting it has consequences so here let's see oh well my score is 85 let's go with a 99 refresh the page and we should see you get an A and extra congrats you get an A+ nested conditional so we could also have an else in there you know else console dot log just a regular a and refresh nothing changes but now if we go with a 95 and refresh you get an A just a regular a alright so that's the basics of nesting conditionals you can continue nesting things further and further generally we want to avoid nesting multiple levels deep past probably two levels it gets a little bit crazy to follow if we had more conditionals and further nested conditionals but that doesn't mean that we need to limit the sort of logic that we implement instead we can take advantage of logical operators so we're going to talk about these three operators here and or and not it's a little bit confusing because I have to use the word and there or and not but they are three separate operators they may be a little bit foreign to you if you're new to programming all three of these operators operates on expressions so basically we can join together multiple pieces of logic or we can negate something to flip it from true to false or false to true we'll start with and here which syntactically is represented with two ampersands and and and for the entire expression to be true if we have an end operator in the middle both the left and the right side must be true so I'm going to show you a very simple example well just start in the console we won't write any code in our file here is one expression we know is true one equals one that's true okay one equals one and here's another expression on the other side of and about two is less than 9 well I did greater than I meant to do less than okay so this part is true and if we put this together with an end in the middle both the left and the right have to be true for the entire thing to be true so we see true but if I change something like greater then all of a sudden we get false as the end results even though this part is true one is equal to one that's true and false true and false I can actually just write that out here true and false gives us false true and true it's the only way we can get true out of this final expression false and true also gives us false both the left and the right must be true so you might be wondering why would you use this well in this example here I'm combining two different pieces of logic one expression on the left and another expression on the right both of them have to be true in order for this to happen in order for console dot log valid password to actually be executed so I'll show you another example over here in our file I guess I'll comment this out too and we'll write another example in this example we'll have two different variables let's go with a color mmm color will be purple and another variable will be animal how about toad okay then we'll write a simple conditional if color equals purple and then inside of that I also want to check if animal is toad animal equals toad if that's the case both of those are true then I want to console dot log I don't know if this is so dumb anyways purple and toad but I want to councils out log Y a purple toad sure so let's run this very quickly refresh the page and we get Y a purple toad okay simple enough but I don't have to write this as a nested conditional statement because of the and logical operator we just covered I could rewrite this like this if color equals purple and two ampersands animal equals toad make sure I capitalized things to match what I have then we can console that log Y a purple toad so I'm combining two different pieces of logic two expressions if this is true and this thing is true then we'll print this out otherwise we can console dot log something else ooh not purple toad sure okay so we should get the same exact result right now yay purple toad but if I change one of them instead of toad how about purple frog refresh the page foo not purple toad both of these had to be true in order for the entire thing to be considered true so it's nothing groundbreaking we could write this with multiple conditional statements nested or we can combine our statements into a single expression like we have here using the end logical operator we also have the or operator which we write using the pipe character rather two pipe characters usually found above the Enter key or the return key on your keyboard on my keyboard I have to hold shift it shares the key with the backslash so it's not an L or a one it is a pipe character and we need two of them so the or operator only requires one side the left or the right to be true in order for the entire thing to be true so as you can see here I've got one not equal to one well that's false on the right I've got 10 equals 10 well that's true the whole thing is true only one side must be true here's another example let's just do it in the console again 1 equals 1 or 2 pipe characters 1 equals 1 well both of those are true true or true gives us true now if I instead called that and had one I don't know one not equals one the whole thing is still true because the right side is true and if I negated this side or I made it false but if I just wrote false the whole thing is now false this is false and this is false left and right are false that's bad well it's not bad but the overall thing is not going to be true because we're using the or operator one side at least has to be true or both can be true so I'll show you an example where this can be useful let's say that we run a theme park or a theater maybe we run a theater and based off of someone's age ticket prices change let's say we have somebody who is 5 years old so if age is less than 8 let's say that someone gets in for free so if age is less than 8 console dot log you get in for free a lot of theaters and places have free admission for children and the same is true if you are a senior in this case senior citizen let's say you're above 65 70 let's do that down here so we'll do another we could just do an else if I guess or just a separate if let's do an else if age is greater than 75 or 70 what's do that may be greater than or equal to well just do the same thing you get in for free otherwise we can console dot log that will be about ten dollars okay so we have two things that have the exact same outcome you get in for free but two different pieces of logic and only one of these is going to be true for a given number right we can't have a number that is less than 8 and at the same time greater than or equal to 70 at least not in the mathematics that I know I guess I don't know I should intercept that I regret this let's run this age is set to 5 make sure that we get what we expect you get in for free I'll change age now to be 50 and we expect to see that we have to pay $10 and I'll change it to be I don't know 79 if I can type it refresh you get in for free now using the or operator the or logical operator I can reduce this here down to a single conditional statement just a single if if age is less than 8 or age is greater than or equal to 75 said what I said I think it was 70 such a bad memory these days will constant that log you get in for free so only one of these is going to be true in this case although if there were a world where both of them are true it's totally fine but with or we're just saying one of these must be true for the entire thing to be true now both of them are false then run this if we had done and it's a very different story as we've seen both sides must be true okay so let's just verify it still works we have 79 as our age you get in for free let's do 6 as our age we should also get in for free but if we do 60 that would be $10 okay so that is the basic idea behind logical or and then finally we have logical nots our third logical operator here it's written using an exclamation point and logical not will return true if the expression that we're applying it to returns false so let me show you an example of that here's a very simple example we have the boolean true if I use not in front of it which negates it it returns false now if I have not false it returns true we can also do more complex things like five equals five triple equals five and then I can put parentheses around the entire thing and negate it and now we get false that's pretty much all I'll show you for now but you can apply this to any other logical expression long or short complex or simple it is always going to take some expression and if that expression evaluates to true when we negate it with logical knots the whole thing is false and if the expression returns false logical knot will return true all right so next up let's talk about arrays in JavaScript we have access to a built-in data structure called the array an array is just a collection of values and those values can be anything it could be comments of or comments on an Instagram post or responses to some tweets could be a collection of levels which are very complex levels in some game so a level needs to include a whole bunch of stuff it's not as simple as just a string like a comment it could be the songs in a playlist it could be the line up for Coachella it's just a collection of values although I guess the lineups not necessarily ordered it kind of is though each line going down yeah whatever it's just a collection of values so here are some examples we have an array called colors which is a collection of strings there's another one called lotto numbers collection of numbers notice the syntax or how we make an array we use the square brackets opening and closing and then a comma separated list of values inside so whatever those values are and whatever order they are in will be used to create an array so I'm going to clear this I'll make this a bit larger here and let's make an array let we can do something easy like nums equals 5 $23.99 and negative 1 there is our number we look at it it has 4 items in it that's what the console tells us right there and there's an order 5 is first negative one is last now I can change that I can move things I can reset or update values but first let's see that arrays have a length property nums dot length is 4 let's make another array how about hens sure these will be some chickens we've got I don't even know Stevie and Edna and it's another hen named Henrietta it's a bit whatever it's a bit generic for a hen but sure okay so here's our array of strings this time and it has a length of three so arrays are collections and they are ordered and they are indexed just like strings are where each elements in an array has a corresponding positional number and index starting at 0 so if I expand them in the dev tools again this is just the dev tools that lets me do this I can see the index next to each value so 0 is stevey one is Edna two is Henriette or with nums zero is five one is twenty three and so on if I wanted to access one of those let's say hens of index and before I type this how about if I did hens of index 2 what would I see if I hit enter well index of zero is stevey one is Edna two is Henrietta and how about nums with index of four here's nums what would I get if I put index of four in well length is four but that does not mean there's an index of four the greatest index is 3 so we get undefined there's nothing at zero one two three four there's nothing there we get undefined so we can also use this syntax to change a value if I wanted to I don't know change the first element in hence I could do hens of zero that's our first index our first element now equals instead of Stevie how about that we realize that it's it's a male it's a rooster hens of zero equals Steven now if we look at hens Steven Edna Henrietta so I can change one element at a time using that index notation square brackets and the actual numeric index here's one more quiz question what happens if I do hens and then square brackets let's say I'm gonna take this hmm can I hide this so you don't see the answer hands of square bracket one there we go square bracket again - what's gonna happen here it's a quiz okay so what does hens of index one give us well index of zero is Steven index of one is Edna but then we have another index of two well strings like Edna are indexed so I can access index of two of Edna which is zero one two four N and that's what we should see indeed it is okay arrays also come with quite a few built-in methods here are some of the more common ones but this is definitely not all of them I'm gonna focus on these four for now push pop shift and unshift they all have to do with adding and removing elements at the beginning or the end of an array so we'll start with push pushes a method we call on an array like hens hens dot push and it expects us to pass in some value that will be pushed onto the end of hens in this case so Steven Edna Henrietta about Edith okay we look at hens now and at the very end we have Edith I could push on again let's do one more how about just a boring hen named Bob now we have Bob at the very end we also have a method called pop and pop will be used to remove from the end of an array we don't need to pass anything in it we'll do the same thing no matter what it takes the last element from our array and removes it and it returns it to us as you can see here Bob if we look at hence now does not have Bob and I could save that to a variable so I could do something like let most this is sad but I could say let dinner n equals hens dot pop and that will be taking the last item in our array and saving it into a variable called dinner hen and updating hens to now only have three hens or three strings in it so we also have shift and unshift which operate in the same way but at the start of an array so unshifted when you're starting out you'll probably mix these two up on shift adds to the beginning and shift removes from the beginning so if we try hens dot on shift who should we add in here how about Norma Norma we look at hens we now have Norma at the beginning and then we do hens that shift rather that will remove the first element which is Norma we just added her in and now we're back to three elements so these are really common methods because as we've seen arrays are ordered they maintain that order and often we want to add elements in or remove elements based off of the order so for example maybe we have an array that is restaurant orders a waiting list for people who have I don't know people who are waiting in line to come to our restaurant we don't have seating ready so we have our first person who is I don't know how about Harry and then the next person in line is Jasmine okay sure so let's call that waitlist let waitlist equals that array now to make this a fair wait list the person who was in the waitlist first which is Harry will be the first person to be helped so we could use which method to get Harry out of their wait list dot and the answer is shift we get Harry and now it's just jasmine now if I wanted to maintain this order how do I add someone into the end some new person shows up and wants to get a table so they put their name down how would I store them here let's say their name is this is the hardest part Brian how do I add Brian in at the end well it is push not push but push oh goodness twice in a row huh here we go and then we'll put Brian right there wait list dot push will put the next person at the end so I could push someone else in hit do just to show you this we can have a mixture of values if I wanted to I could have numbers in there they'd put a boolean in there weird in this case but fine so push will add to the end and shift and removes in the beginning now there are these other methods can kat includes index of join reverse slice splice sorts we're not going to go over them here there are many of these and they're useful they're very useful there's actually a bunch more methods we're not going for things like map and reduce there's a reason this YouTube video is not 20 something forty hours but those are essential methods that you should come back you should circle back to and learn at some point but just to give you this intro that's that's one of the sacrifices we've had to make I'm sorry array methods you are important just not important enough next up a note about using Const and arrays so as we've seen with Const at least so far if I make some num I'll set it equal to 99 if I wanted to change num num plus equals 1 or num equals 100 not allowed at all I cannot reassign or update the value in a constant which I've declared using the Const keyword but if I use constant array let's go with colors let's just do red orange and I don't know how about teal I use Const here which you might think means that I cannot change anything about colors but that's not actually the case if we look at colors here it has three elements red orange teal if I push on or use on shift or shift or pop it or any of the other methods that change in array it's allowed even if I'm using Const so colors dot push how about purple we look at colors first of all we didn't get that scary red error message that we got earlier it's totally fine and the reason for this is that when we use Const and we set it equal to an array what is actually being stored and what cannot change is the reference to the array not the contents think of it as an egg carton I guess where that egg carton has to be there but it could have one egg or 20 eggs or 50 million eggs it doesn't really make sense at all but we can change the contents of that array but what I cannot do is suddenly say actually colors equals a new empty array or a new how about just a number I can't do anything like that I can't reassign it but I can change the contents of that array so this is very common to use Const with arrays because usually we don't want to reassign some variable to be a brand new array we want to keep the same original wrapper the same container in memory now another thing you should know about a race now that we're talking about them is that comparing them does not work the way you might expect if I have the array 1 2 3 and I do triple equals 1 2 3 it is not going to be true why not each one of these every time I use square brackets I'm making a new reference in memory you can think of it basically as a location in your computer's memory and that location is unique so even if the contents are the same it doesn't matter triple equals is not going to look at the contents it just looks at the places the locations in memory so I'll show you another example if I do Const a equals 1 2 3 and then Const B equals a they are now references to the same thing in memory a equals this in memory and then B equals whatever a is so it's like two arrows pointing to the same thing we look at a we look at B they're the same and if I change something how about I push four onto a let's look at a let's look at B both of them have those changes and now if I do a triple equals we get true because they are one reference in memory so if we do have different arrays that are not the same reference and you want to compare them it's a little bit trickier you have to look at the values you can't just rely on triple or double equals if I try double equals empty array equals empty array it's still false triple equals it's still false it's comparing the address in memory which is not well it's not quite the address but it's comparing the reference think of it that way okay another thing that's very common with arrays is to have nested arrays which are also called multi-dimensional arrays so here's an example a pretty common situation where people use nested arrays would be with some sort of game board like a two-dimensional game board checkers board a tic-tac toe board let's do just tic-tac-toe sure where you have three rows that make up a game board or we could do three columns it really depends on how we want to structure this but imagine we have three rows going across each has three elements in it so we would have our first row which maybe has X X and then o and then we could have our second row which will be O let's see X and X and then our third row which would be I'm making this up here so we have a tic-tac-toe anywhere X yeah that should be a tic-tac-toe right if I put an X there so if I hit enter here my game board array is now an array of a race and it's easier to see how it's a game board the way it's displayed here it's exactly the same this is just the dev tools making it look slightly nicer so how would I print out this middle X right here let's say I wanted to change it to be something else I decide actually that was supposed to be an O I don't know why but I want it to be a no how do I make that an O well it's the same idea as what we saw earlier where we had a string inside of an array where we used our first index to unwrap one layer of the onion that right there and then our second index inside of that array so we'll do game board and do this as an exercise if you'd like try and change that X here the middle X to be O so game board of and then what's this index here zero one there's only three different items 0 1 2 we want index of 1 that gives us the middle array and then we want the middle index of that which has an index of 1 0 1 and then I'm going to set that equal to something else and oh and I'll do an upper case oh just so we can see it for sure we look at our game board now and we have an upper case oh right there it's a long story short nested arrays are frequently used to make game boards and other data structures that's a horrible sentence but they're used a lot in programming except we move on to a completely different data structure it's built into JavaScript as well and it's called the object object literals specifically are what we're going to focus on right now objects are collections of key value pairs each key value pairs what we call a property so rather than having an ordered collection like an array where we use an index to access elements give me the twentieth element or give me the first element index of zero rather than that which is an array with objects we use key value pairs as you can see in this little diagram I made on the rights we would say something like I want age or set age to 20 what is city or is admin what is zip so key value pairs a key which is what's shown on the left and then a value which is what we have on the right they don't have to be strings it could be numbers boolean it could be an array another object we haven't talked about things like functions but we can put functions in there there's a lot of stuff that we can do for those values but let me show you the basic syntax first I'll clear this and we'll make our first object frequently more than frequently most often you'll use Const instead of let for the same reason that we used constant with an array it allows us to still change the contents of the array or the object but you can't reassign the variable to a new object or a new array okay so const let's just go with person and then curly braces curly braces instead of square brackets so that makes us an empty array this will make us an empty object and an object consists of key value pairs so we have to specify both of them and the syntax for that looks something like this let's go with age will be 19 what else do we have about a person how about a first name will be archer sure okay so you can see already we have key value pairs they're separated by a comma and within each key value pair we have a key and then the colon or a colon and then a value and notice I'm not putting quotes around age what is that if I just you know copy this for a second no there we go if I just typed age like this well I have a variable called age that's unfortunate how about first name I don't think I have a variable called first name I just type that on its own I get an error but if I add quotes it's totally fine now if we go back to this line what actually happens here is that these keys age and first name will be converted into strings for me this is just a nice shorter syntax so if I look at my person object now they don't look like strings but this is definitely a string and this is definitely a string age 19 first name archer that is the very very basics of setting up an object now how do I get information out of an object all I need to do is access the variable and then I use square brackets again which is kind of confusing but instead of passing in a number like zero I'm going to pass in a key like H this is one option person square brackets age gives me 19 so think of a key as like a physical key to open a lot you know the thing you're looking for I'm looking for age I'm looking for a first name but we don't know the corresponding value that key hopefully unlocks that value let's do person of first name and we'll get Archer we also have an alternate syntax person dot age where I don't use quotes I use the dot syntax and I get 19 now you might recognize this from things like length length is a property that is added automatically to an array or a string where I can use that dot property or dot length but I can also do this right here this syntax I just showed you okay now you might be wondering hmm is a string an object it looks like we have the same syntax we're not going to open that can of worms but that is an interesting topic in JavaScript let's ignore it why do even anything about it okay so yes you can make an object with curly braces you can add your key value pairs like this but what if I want to add something in after the fact person needs to have a last name so I can do that using the same syntax I can do person dots last name or person square brackets last name equals and then set it equal to something like I don't know would be a last name Archer I don't know if Sanchez sure now if we look at person we have age 19 first name archer last name Sanchez key value pairs an array technically I guess you could think of as key value pairs where the keys are all new numbers they're all numbers numeric indices and they are ordered in an object we can use whatever we want as the keys although they will be turned into a string so I can illustrate that one more way if I do person of I could do person of 100 equals 100 for some reason if I wanted to do that and then if I access person of 100 we get 100 out but if I add quotes around that you'll see that it also works so I'm turning it to a string now and it will be compared to 100 that key which is a string as well so you can see right here there it is or if I just pass in a number JavaScript will turn it into a string and look for that key which is a string and if it doesn't find it what do you think I'll get if I do person of how about City person dot city well this was a horrible exercise because you already see the answer we get undefined just like accessing an array or a string of index 100 that does not exist we get undefined there is not a value there it is undefined so objects are key value pairs the keys will be turned into strings technically there's something called symbols we're not going to go into it's another one of those topics I am shelving for now if you check out well I don't want to sell you on anything but if you do check out my more in-depth JavaScript of course I spend some time talking about symbols and go into a lot of detail I also have another YouTube video on that so if you're curious anyway I guess you could say that for pretty much every topic in this short course you know arrays we spent 10 minutes 15 minutes on in my JavaScript courses we spend a couple of hours on them okay so key value pairs where of us I totally sidetracking myself here right keys need to be strings or symbols and if they are not a string they will be turned into a string and values can be anything so we've only been using strings and boolean and boolean strings and numbers here but I could put an array on person I could say person dot friends equals an array and this could have I don't know whatever I wanted in here I could have Tammy and let's do one more friend how about panda sure Tammy and Panda now if we look at person we have a couple of properties remember each one of these pairs is a property key value equals property so we have 100 is a string 19 a number and then we have friends which is an array the value for friends is an array of two items we can put whatever we want in here and objects are incredibly common and what's actually very common is to use objects in arrays together so this is a simple example but in the real world if this was I don't know let's say a very horrible social network the friends array probably would not just be an array of strings it might be something like this where it's an array of objects and each friend has a first name like Tammy and then how about an age like 30 a user named Tam Tam and so on and then we would have another object for the next user so why don't I actually fill this out real quick we'll have another person first name will be would we have panda sure and age will be two 73 and what else did we have username will be panda man okay now I'm gonna save this to a variable Const friends okay and what I'd like for you to do here just you don't have to type anything out but how about this I would like for you to average both ages here this is a bit more complex so you'll need to don't just do 30 + 73 divided by 2 don't cheat like that pretend you don't know what these ages are and grab them from friends so how would we access age for this first one and age for the second one add them together and then divide so pause if you'd like to try it write it down but it would look something like this friends of 0 that gives us the first element in the array well that's just this object and then within that I want age so I can do this or I can do dot age and I'll probably just take that and do the same thing so add that to friends of one to give me the next friend dot age again we get 103 and then we're supposed to divide right - if I just divide by 2 here it's not exactly accurate we want to add parentheses and divide by two so that the division happens after we add them together and we get 50 1.5 really that doesn't matter the point here is just making sure you can access something from an array and then a property from an object now this data structure is still quite simple for the real world we would have things probably in here where we might have nested objects and arrays and more objects and so on things get quite complex when you're trying to represent I mean just I mean a person it's about one of the most complicated things that you could try and represent but even just a user for let's say Instagram you've got a store friends or followers and then people what do you call them following versus followers follow ease you've got to store posts and stories and comments and likes and so many different things just for a single post or a single user you've got tags people who have been tagged hashtags geodata or locations that have been tagged in an image there's so much going on but at its core we could structure just a bunch of arrays and objects together to represent that data and that's what a lot of programming is especially in java scripts other languages have different data structures built in and different names instead of an object like in Python we would use the term a dictionary but it's the same concept a key-value data store anyway so those are two very essential data structures that build upon other pieces of data data types like numbers and boolean and strings data structures like a raisin objects use those smaller pieces numbers and so on and store them they structure them so next up we're now going to talk about loops loops allow us to repeat things whether we are just printing a message out over and over and over or printing numbers from one to ten really trivial beginner things that nobody really does in the real world or we are doing something more realistic like looping over an array of comments and for each comments creating an actual comment in the browser that you can see with HTML and CSS or for each tweet displaying the tweet image there are all these things that we do where we run some code maybe a hundred times or a thousand times so this is where loops come in loops allow us to repeat things and there are multiple types there are four loops while loops four of loops four in loops and we're going to begin with the for loop so the regular old for loop is a little bit intimidating if you're brand new not because it's complicated or difficult but the syntax can be hard to remember when you're starting out so if you see what I've written here this honestly might just confuse you more this is the the pattern that we follow for some initial expression with some condition some increment expression inside of parentheses it doesn't seem to make much sense but I promise you there is a method to this madness here is a loop where we have those three pieces one two three separated by semicolons inside of parentheses this first thing what I call the initial expression is going to run the very very beginning it's going to run at the beginning of our loop where we're making a variable called I which is relatively standard or conventional you just want a short variable name one of the only times really I is an acceptable variable name because it's just a placeholder it's just there for your loop anyway we have an i variable that starts at 1 then we have what I call the condition continue running this loop as long as I is less than or equal to 10 and then each time through the loop we have our increment expression I plus plus which if you're not familiar with if we have some variable let I equals 1 if I run I plus plus we look at I it's now 2 it's the same as doing I plus equals 1 it's just slightly shorter so we would read this as for the variable I starting at 1 add 1 to I each time as long as I is less than or equal to 10 run this code console dot log I so very simple we're just printing out a variable I let me write one of our own over here let's make our own for loop for let and again I is pretty standard let's start with I at 0 and we'll run this loop while I is less than 10 I plus plus or we can do plus equals 1 but plus plus is very common and then in here I accidentally deleted my parentheses there and here we can console that log in the loop and then I'll also print out I so we can see what that variable is now I'm going to refresh my page over here and we see in the loop 0 1 2 3 4 5 6 7 8 9 so I started at 0 we printed it out then I had 1 added to it and the process starts over now I is 1 we print that out I has 1 added to it so it's to print 2 out and we keep going as long as I is less than 10 as soon as I is not less than 10 so once this loop runs the final iteration I is 9 I has 1 added to it I plus plus it becomes 10 this is now false and the loop finishes so we could change this up a bit I could do something like I plus equals two now what will we see printed out take a moment and ask yourself what numbers what we see printed out so I begin to at zero we will print out zero then we add two two I so the next time through it's equal to two and we print that out and then we add two more so we get four and six and eight and then we add two more after we print out in the loop eight I is now 10 is not less than 10 10 is not less than 10 10 is equal to 10 so this is all we would see 0 2 4 6 8 let's verify 0 2 4 6 8 and then in the loop I collected to mention that part okay so we're repeating something multiple times it really depends on what our variables are and how we're incrementing them and what the conditional is one thing you definitely need to look out for is an infinite loop this is something that is surprisingly common when you're learning but also if you're just being lazy as a developer or having a if you're particularly tired or you're not paying attention an infinite loop is when your loop never ends so here this will end I is equal to 0 we're adding 2 as long as it's less than 10 so at some point it's going to become more than 10 but what if I had messed this up and instead I did I - equals 2 I'm not going to run this because my browser will get very angry with me it's not the end of the world in your browser usually at least in Chrome my browser window gets a little bit it freaks out my computer gets hot I closed that window eventually or Chrome will tell me something's going wrong and I can force quit it it's not the end of the world but it's annoying I'm not gonna do it I will start at 0 and then we subtract 2 so goes to negative 2 negative 4 and it's always less than 10 it will never be greater than 10 because we're always subtracting starting from 0 or another thing you might see is something like if you ever first I wouldn't do this but if you ever wanted I to equal 10 and then let's say we started at 1 and we're adding 2 each time through this is kind of a Genki thing I don't know why you would do this I will start at 1 then we add two so I becomes three and then we add two more becomes 5 and then 7 and 9 and then 11 it skips over 10 we're never equal to 10 anyway it's kind of a janky thing honestly you probably would never do that but that's the basic syntax of a for loop it allows us to repeat something so why don't we do something it's not much more interesting but let's let's do a little practice where we print out the squares the perfect squares which would be things like 1 times 1 and 2 times 2 and 3 times 3 so 1 4 9 and then we have 16 25 and so on we just create the numbers from 1 let's go from 1 to 20 and print out each perfect square based off of those numbers so I want to see one printed out and then 4 and then I've already forgotten 9 16 25 all the way up to 400 which is 20 times 20 so we're going to use a for loop I'll comment this one out I think I'm actually just going to reset it back to the beginning for loop that we had just go with I plus plus so you have that available to you and I'll comment it out now to create this for loop will call this perfect squares 1 to 20 I'll add a little comment we'll have a 4 let doesn't have to be I but very common and we'll start it at 1 we don't care about 0 times 0 we will keep running while I is less than or equal to 20 because I do want I to be 20 I could also say well I is less than 21 but I like less than or equal to 20 I've plus plus we'll just add 1 to I each time ok so I will be 1 add 1 each time as long as I is less than or equal to 20 and we can always just check our work by just printing I first okay there we go 1 all the way down to 20 now to get the perfect squares I just multiply times i refresh and now we have 1 times 1 2 times 2 3 times 3 all the way up to 20 times 20 which is 400 so here's another little quiz or exercise I'd like for you to print out the numbers from 50 to 40 in reverse order so 50 49 48 all the way down to 40 okay so give that a shot you'll need a for-loop same pattern but different numbers here is the way I would do it I'll comment this one out let's just do I don't know count down backwards 50 to 40 forward let I equals and we're gonna start at 50 and we're gonna keep going as long as I is greater than let's do greater than or equal to 40 each time through we will subtract one which could be minus equals one or I - - it's the same shorthand I plus plus it's not exactly the same obviously but it's the same pattern this adds one to I this subtracts one or decrements I so we start at 50 we subtract one each time through as long as I is less than or equal to 40 we keep running the loop and let's just call that log I let's see if that works for us so I'll refresh and we get 50 49 48 all the way down to 40 yay next up we have another type of a loop called a while loop so a while loop is relatively simple the syntax is definitely shorter than a for loop all that we do is pass in one condition into a set of parentheses and as long as that condition is true which we would call the test condition as long as it's true the loop continues to run so it may not be a set number of times like a for loop we go from 1 to 10 or 50 to 30 or whatever it is with a while loop we could have something like while there are no new emails or while our queue of jobs is empty or whatever it is we can have some condition that may not lend itself as much to a for loop but we can also recreate exactly what we've already done using a while loop so for example over here we're counting backwards I could rewrite this as a while loop it would look something like this while and we would need to initialize a variable first let I equals 50 and then while I is greater than or equal to 40 we will console that log I and then we will I - - so same principle it's shorter here it's easier to mess up if you're doing doing a while loop because you have to remember to decrement you have to make sure you're not causing an infinite loop but this is basically the exact same thing let's just verify that so while I is greater than or equal to 40 printed subtract 1 let's refresh our page here and there we go our first batch goes from 50 to 40 that's the for loop and then 50 to 40 that's the while loop now we're a while loop becomes more useful and more interesting it's when you have something that maybe it's not just a set of numbers or a sequence like what we have right here but maybe we have a game and we want the game to continue while you have a number of lives it corrects that I don't know number of lives is greater than zero that might be an hour it might be a decade depending on how good you are at this game let's make it very simple I wouldn't even call it a game let's make a password guesser and to do this I'm going to introduce a new built-in function you have not seen before we've talked about console dot log which we can use to print something another thing that we have here is called alert which is really annoying alerts you call with parenthesis just like any other method we've seen that will actually execute it and whatever we put in here it will actually be alerted to us in a little pop-up window so this can be quite annoying if it's abused and the other example or the other method I'll show you is called prompt and prompt is going to accept some value here like some sort of prompt a string like enter your name and when we hit enter here it pops up with a little window where we can actually type something in now we're not doing anything with it but I could capture that so I could do something like this let username equals prompt enter your name so now whatever I enter in here how about pizza face one two three if we look at user name it now has that value and notice that it's in quotes it's a string it's going to stay a string we can try and convert it we haven't talked about that and it's beyond the scope of this video but if I did type in a number in there like 2 and if we look at user name it's the string 2 okay so now that we have a way of getting user input a very simple primitive way typically we would write up make a form with HTML and CSS and have some fancy layout but prompt is a very easy way to get some tiny piece of information let's hop over here to our javascript file and what I'd like to do is make a really really simple demo with a while loop where we're going to have some password you're trying to guess what password equals and let's have it which we have it equal let's just set an initial password a very simple one to remember like lol then we're going to have a user guess using prompt so prompt enter the password and we'll save that to a variable let's guess equals prompt and then I want to repeat this process I want to keep asking for a new guess as long as the user has not correctly guessed password so I can use a while loop while guess is not equal to password keep running this code so what do I want to do when guess is not equal to password I want to get a new guess again so we start with our password it never changes at least not while the code runs then we initialize guests based off of some input a user types thanks to prompt and then we're going to check is guess equal the password if it is then this never runs but if they are not equal then we get a new guess and it runs again are they equal now get a new guess and keep going until at the very end we can add something in here like console that log you got it right so this will only run when this finishes so let's see what it looks like I'm gonna refresh the page and enter the password I'll enter in hello nope enter the password again nope lol we made it so what might be slightly nicer is to add a console dot log in here console dot log please try again something like that repeat this enter the password nope please try again please try again lol we got it right so here's a situation where a for loop would not really work for us we don't have something running a set number of times it might happen the very first time we might get password correct immediately or it might happen after a million times or Never hopefully that's not the case but it's possible so a for loop like we have here it's really commonly used when there's some set number of iteration so you want something to run 10 times or or a hundred times or five times or whatever it is a while loop can be used to do that as we've seen here we can use numbers and increment and decrement but it's also commonly used when we have something that runs an undetermined number of times indeterminate undetermined anyway so that's a while loop the final loop that we'll take a look at for now is the for of loop and this is a really commonly used newer way of looping it's new ish which is why it does not work in Internet Explorer unfortunately it is a way of iterating over arrays and other iterable objects we won't get into the exact meaning of that iterable objects but we can iterate over things like strings as well using for of so before we do anything with for of let's talk about how we would iterate over an array suppose we had this array of purchases let's say this is I don't know where we're traveling and this is the the purchases we've made recently whatever it doesn't really matter let's just pretend it does make sense it's an array of purchases if I wanted to total them together or even just print out each purchase but that's kind of silly to print something to the console but imagine I wanted to do something with it I wanted to subtract it from a bank account or I actually wanted to if we had a payments applicator a payments platform we had builds or that we're integrating with I actually want to charge a user for each one of these I need to actually send a request and bill them using stripe or something so I need to do that for each element in here we could loop over using a for loop and generate an index and numbered so start with zero and then go to 1 and then 2 then 3 then 4 then 5 and 6 and 7 so we could do a for loop like this for let I equals 0 well I is less than purchases dot length add 1 to I each time through I could do this console dot log purchases of I I'm just generating a number I goes from 0 up until the last index in this array remember that the length is always one more so we don't want less than or equal to we want less than the length of an array and we add 1 to our index so let's see what we end up with this should just print out each value 1999 up to 285 how would I sum them all together there's a simple hopefully a simple exercise how would I put them in a variable that had a total well I would do something like this let total equal 0 and then inside of here total plus equals purchases of I naught I remember I is the index so we'd be summing 0 plus 1 plus 2 and so on we want the actual elements at that index and then at the very end why don't we console that log total is and then we'll print out total I could also use a string template literal if I prefer to do that I could do this total is and then we need our dollar sign curly braces our total variable and I'm actually going to put a second taller sign there just kind confusing this one will show up as a dollar sign you can see it's green here not blue so it will be there because it's a price I want to display let's see what we get Oh lovely we're not gonna go into rounding in JavaScript so we'll just go with this many decimal points some of that is just great but it seems correct I think 258 is that yeah I guess we got about 200 there yeah anyway so we were iterating over an array but we're not doing it using a for loop we're making a regular for loop we're generating an index but there's an easier way which looks like this for some variable of some iterable do something so I could rewrite this what I have right here I'll keep the original and commented out and rewrite it down here using a for loop so for some variable so we'll come back to that we'll call it X of some iterable which is going to be an array so for X of purchases instead of X we need to come up with a variable name that makes sense X would work it's just not very logical or well it doesn't make sense so let's leave it at that so whatever this variable is it is not going to be an index it's actually going to be each individual element so I would go with purchase or price or item transaction I think I don't know purchase is kind of long for purchase of purchases but I guess that's that's relatively clear it's just kind of long to type inside of here that variable purchase every time through the loop will reference one of these elements starting at $19.99 then 9:50 all the way until the end and then the loop will finish so if I just print out purchase right there I'm not gonna print out the total just comment that out we should see the exact same thing 1999 - to 85 so we don't have to deal with an index you don't have to do with deal with the length and starting at 0 and I plus plus we can but if we just want the actual elements a 4 of loop is very very easy come up with some name here that's descriptive some variable of some iterable and then we can print out each thing or we can do something to each one so why don't we add it to total total plus equals purchase and then we can print out our total down here and hopefully we get the same exact total and we do such a lovely number okay we can also iterate over things that are not arrays as I've mentioned very briefly there are other iterable objects we're not gonna spend much time on this but you could do something like this for let character of some string that string is something you can loop over let's console dot log character run this again and there you go you can see each character print it out not that common to do but it is something that you can alright so that's enough of looping for now we've seen three main ways to loop the first one is a for loop the second one is a while loop and the third one is a for loop which allows us to easily iterate over some array just remember it does not work in Internet Explorer so we've got one more big topic that we have to cover this would be incomplete if we skipped functions functions are really at the core of java scripts they are probably the most important concept that you need to understand to be a competent JavaScript developer functions are really just reusable I hate reading my slides like this reusable procedures but that's what they are they are things bits of code that have been wrapped up and given a name that we can then call again and again and again some chunk of code that we can execute later and we can also do things like pass in arguments so as an example of why we might want a function take a look at this code that we just wrote right we have an array of purchases we are totaling them all up by looping over and adding each purchase into a total variable and then we print the total at the end now what if I had another array of purchases for somebody else or this is an application and I wanted to run this code every single time somebody added an item to their shopping cart so if I wanted that to happen let's say I just had a second array called two purchases two or tommy's purchases I would have to repeat all of this code and that would be really annoying so that's where a function comes in we could write a function called get total or a calculate total and we could pass in purchases and get the same end results by making this reusable modular function so with functions there are two steps we define our function and then we execute or we run the function so we'll start by defining a very very simple function and comment this out we'll start with a function called laugh and all that it's going to do is console dot log haha so the simplest way to define a function is using the keyword function and then a function name which is usually it's just like a variable camelcase except the first letter is lowercase so in this case if I just do laughs it's all lowercase but laughs loud would look like that you can do whatever you want but typically it's camelcase so function laughs and then we have parentheses and then we have curly braces and inside of these curly braces I'll write some code so let's do a console dot log hahahaha and then maybe how about hehehehe I don't know I said how you spell hehehe and then let's do hahah again so just three lines three useless console dot logs and I have written them inside of a function that I've named laughs okay so if I run this code right now where is it here it is if i refresh nothing happens I don't see anything because I've only done the first step which is defining my function I now need to execute my function and think of how we execute a method so a method like to uppercase or any of the array methods like push or pop those are just functions a method is a special type of a function but they're functions so we have to use parentheses to execute something like a string dot to uppercase this is not going to work I need parentheses to actually run it same thing here I've defined laughs now I have to call it with those parentheses so now if i refresh the page there we go ha ha hee hee hee ha ha ha ha I can laugh again and again and again ok so that is the first thing to understand about functions we define them and then we call or we execute a function now there are other syntaxes for how we define a function another option is called a function expression where we can save a function in a variable so we had laughs what about laugh-out-loud will be another function function and this time is slightly different I don't give this function itself a name I'm storing it in a variable with a name it's it's really nothing we need to care about at this point just worry about this syntax but now that we're on this topic another thing you might see our arrow functions this is a newer feature in JavaScript something that if you are serious about JavaScript you definitely should consider learning I have a pretty thorough video on that as well but for now we'll go with our standard function declaration their function statement is what it's called so function keyword and then a function name and then curly braces some code inside it will not be executed automatically we have to manually call that function with parentheses ok so the next thing we need to understand our arguments arguments is actually a term we've already talked about when we saw things like index of or push for example we have some array Const data equals an empty array and then we call push we need to pass in the thing that we want to be pushed onto that array this string in this case is a string is an argument it is information we pass in inside of those parentheses to push so if I wanted to make a function I guess we could go with laughs where instead of just ha ha ha hee hee hee ha ha ha every single time maybe I want this how about I want to specify how hard someone is laughing so how many ha ha is we get so it might be something like this ha ha or it might be ha ha ha ha ha ha I want it to behave differently based off of an input well the way that we accept an input is by adding a parameter right here inside of these parentheses on the function definition put something in here like should we go with level or loudness sure loudness is fine now loudness is going to be a variable that we have access to in here I can console dot log loudness just like that and let's see what happens right now if I call laughs with no arguments passed in what do you think loudness will be well let's see it is undefined but now if I call laughs and I do pass something in like a string I'm just gonna put something random in there that is loudness now if I pass in a number there's our loudness once again this is just a placeholder it's just a name that we've made for the first thing that is passed in so let's assume it's going to be a number like we're gonna call laughs and pass it a number like 5 what I'm going to do is use the string method repeat which we have seen before but if I do ha dot repeat 5 we get ha ha ha ha ha ha I think I said it 5 times and if I do it 10 times we get ha ha ha ha and so on 10 times so I'm gonna use this loudness to indicate how many times or just to control how many times we repeat these characters now loudness doesn't really make sense it's really more the length of the duration I don't know maybe I'll call this level laugh level okay then here I'm just going to quickly replace this ha dot repeat laughs level now we do have to be careful with how we call this function right if I pass in something that's not a number it could break things but that's all that's a bigger topic to figure out whose responsibility it is really to to define a function that handles every possible screw-up if it's on the the person who's calling a function to recognize how it works anyway let's just go with this a single line hot repeat laughs level so now if I call laughs five we get that I call laughs ten we get that and laughs 100 we get that we have made a reusable chunk of code that is not only reusable it's not the same thing every time it also has some degree of flexibility where we can actually manipulate the behavior based off of a single input and we can also have multiple arguments so instead of just a laugh level maybe we could also add in a name the person who is laughing so our console dot log could be something like Connell says hahahahaha or Marianne says ha and that sort of thing so laugh level and then we'll have laugh laugh err maybe just name and I'm just gonna start by printing out the name so you can see it's name is name and right now I'm just calling laugh with five what do you expect to happen what will we see when this prints out and when this prints out I'm just passing one thing in well all that we see is name is undefined but we still get our five Haws because it's all dependent upon order so whatever we pass in first it happens to be the only thing we'll be assigned to the very first parameter here so it's about order it doesn't matter you know if this was a name like Connell here it's still going to be saved or stored in laugh level which will probably break things we'll see what happens here repeat is expecting a number okay it just doesn't repeat it at all just gives us an empty string it looks like just the equivalent of that so now let's actually pass in a name as the second value and then laugh level as the first and we should see name is Connell ahahahaha we got nine repetitions of ha so we can use that name now I think what I would do is probably save this into a variable Const I don't know probably just pause I guess that looks like has what should we call that instead laughter sure and then we can counsel that log and then I'll use a string template literal to put the name in here name says and then another embedded expression dollar sign curly sign dollar signed curly braces laughter okay let's see what happens refresh and we get Connell says hahaha let's laugh again four times and it will be Marianne Marianne says ha ha ha ha ha and if I leave that off undefined' says ha ha ha ha ha hmm so if we wanted to add in a default value this is probably a bit more than we need to go a bit more detail than we need for right now but if we wanted to we can use an equal sign here and then pass in some default in case there is no name specified so name can be anonymous maybe and last level can be I don't know one so let's see what happens now if I call laughs with no arguments anonymous says ha but if I do pass in how about 45 we get anonymous says and then 45 repetitions ok so that's the basic idea of arguments it's all based upon the order that we pass arguments in JavaScript doesn't care about the type so even though we know in our hearts we know that this should be a number javascript is not gonna stop us from passing in something that's not a number it just might give us an error message we might have something go wrong in the function but there's nothing in place that says this has to be a number or this has to be a string now the last concepts we need to discuss around functions is returning values in the return statement right now this function every time I call it is going to print something out and we can actually see that here of course we can see it here I don't know why I said that that was idiotic we have been seeing it it prints something out but what is this undefined wise it keeps showing me under find well let's compare it to something like pop so we call some string I don't know why I'm doing a string it's an array let's have the array 1 2 3 dot pop when I call that I'm getting a number showing up down here what this number is is the return value we've talked about this briefly it's what the function the method pop gives me back it's not the same as printing it so if I wasn't doing this in the console and I pop something off we won't see it in the console if I just did it in a file over here I have some array and I did pop it's just gone unless I captured in a variable a return value is kind of what it sounds like it's the thing that a function returns that we can then capture in a variable or pass to another function or reuse in some way so let's write a function that does return something let's do something very simple how about a square function I know it's not very exciting Square will accept a number and if we call num of 4 we would expect it to return 16 we could begin by just printing out the square so nice and easy console dot log we could do num times num or we could do num star star 2 to raise it to the second power sure so right now no return I'm not writing the word return I am just printing something so when I call square of 7 we get 49 printed out but then undefined is a return value we did not define a return value so printing something out again is something we do when we're starting out or we're debugging you're watching a tutorial like this but in the real world we're not going to be constant out logging very much at all like if you go to a website right you're not typically looking at the console to see something so usually what we do is we would call square of 7 and then capture it somehow capture that return value in a variable or do something with it I don't know why you know append it over here make a button with it that seems silly to do with square of 7 but let's say we had a function called you know get latest tweets or something we might want to call that and then do something with the return value the latest tweets they might be in an array or something so printing is very limited it's not really what we want all we need to do instead is use the return keyword and then return something we could do this in one line like this return num star star - if you prefer you could make a variable first like Const result equals that and then return result it's kind of unnecessary here because this is nice and short so I'll just do it in one line return num star star - okay so now if I call this function I'll refresh the page I already called it square of 7 I don't see anything here it's just lost that is how a return value works if you don't capture that return value if you don't use it so I could save it to a variable Const how about just results equals square of 7 I'll refresh and if I type results in my console you can see 49 so if I call square of 9 we get 81 yes it's showing up here but it does not console dot logged so I could save that to a variable now Const answer AWS or ans equals square of how about the square of 13 we now have 169 169 stored in this variable so the return keyword is how we can export a value how we can ship something out of a function and to capture it somewhere else we also can do things like what if we had a different function a really simple one but we'll call this add add will accept two numbers how about just X and y and it will return X plus y nothing crazy just refresh over here I'll show you how it works add 2 comma 5 we should get 7 returned all right so I can use one return value and pass that in to another function so what if I did something like how about add one maybe five and in seven that will give us what twelve and then I'm gonna just take that directly and pass it in to square so this is going to be evaluated first five plus seven should give us 12 and then that will be passed into square because it's returned from ad you can think of it as just replacing this right here twelve square of 12 is what 144 I think let's see just run it over here yes there we go all right so some simple examples of return values and using the return keyword one thing you definitely need to be aware of is that whenever you return something from a function that function is done executing so if we had something after this console dot log I that code is never ever going to run if I call square you can see we never console dot log high-return short-circuits it stops the execution of the function now return has to actually run so if we had a conditional in here for example if we didn't want to add negative or square negative numbers we could do something like if let's just say num is greater than 0 return num squared otherwise down here we can console that log not allowed so this code will run in certain scenarios what I'm trying to say is that just that the keyword return on its own it's not enough to just stop execution this line actually has to be run so if you pass in a negative number this will not run in here and this runs I guess I should demonstrate that if I call square of 1 it is returned to 1 times 1 but if I do square of negative 2 we get not allowed this line never was executed ok so returning is a really important piece of functions really really important we have inputs which are arguments that we can pass in like here seven and then we have our outputs from a function which is really just one output a single return value now you cannot return more than one thing you could return an array you could return an object if you had multiple values you can combine them into one data structure but you can't return like five different strings unless you combine them in some way until one entity so that's returning alright so now what we're going to do is combine some of what we've seen not every single piece but some things variables conditionals functions return values a couple other things to make a very simple guessing game again very very simple nothing crazy not really anything you want to write home about but the goal of this video is not to build something impressive it's to get you just comfortable with the basics this is a process if you're legitimately just starting out and this is the first thing you're learning in JavaScript or the first sort of taste of JavaScript there's a lot more to javascript in and there's a lot more that goes into learning it it takes time it takes practice so unfortunately we can't build anything mind-blowing but it's simple it's it's better than nothing so we get a prompt please guess a number these numbers are between 1 and 10 for now although you can change that let's guess 1 and you can see it tells me and this time I console dot logged it one is too low so please guess another number all right let's try 9 9 is too high all right how about 5 5 is too low another thing I'll show you is said if I type something that is not a number well like a string here text please enter a valid number I'll keep trying that it keeps asking me to enter a valid number now let's try that see 5 is too low so maybe 8 8 is too high ok 7 I win and that's it so nothing crazy but I will tell you in advance that I did use a lot of not a lot but a couple of functions to make this work if you would like to try this on your own definitely give it a shot there are a couple of things that we have not covered in order to make this work one of those issues that you'll run into is dealing with what happens if you use or enter something that it's not a number they enter like that how do you compare that the other thing is generating a random integer from 1 to 10 but we'll go ahead and run through this together ok so the first thing we want to do is pick the target number we want to pick that initial number and we've seen math dot random which gives us a random decimal from 0 to 1 doesn't include one but 0.9 or whatever so it gives us something like this that would be one of the the results that we get back now what I'm trying to do is pick a random number from 1 to 10 an actual whole number an integer so without boring you too much the the stock way that you do this is using math dot floor which is another method on that math object math includes a whole bunch of these methods floor is going to take something that has a decimal and just chop it off so math dot floor of twenty-three point nine nine nine nine nine nine is just twenty three or twenty three points 0:01 it's still just twenty three now if we just floor math dot random we're always going to get zero because math dot random is between zero and one but if I multiply this by ten for example now I'm taking some random decimal from zero to one multiplying it by 10 and then chopping the decimal off so we get nine seven six but we also get zero so if I want this to go from one to ten I also need to add one at the end this is just a stock a very common way of doing this it's kind of annoying other languages have a simple way of doing this like generate or random int we don't have that in JavaScript so we'll save that to a variable let's call it targets or target num okay and then we're going to ask a user to make a guess so something like how about just let guess equals prompt enter a number all right now we have our first well there's a bunch of hurdles that if one hurdle here is that prompt is going to be stored as a string even if I enter a number so if we look at guess if I enter 8 here and I look at guess get rid of this come on it's the string 8 so I want to turn that into a number and the way that I'm going to do that is using something we have not talked about called parse int where I can pass in like a number 8 and I get 8 but I can pass in something like 30 the string and get 30 out if I have a decimal it's just going to ignore it which is fine because we're only dealing with integers there are other ways of converting a string to a number parse int is simple enough for now so we're going to call Parsons so let guess equals prompt enter a number we could just do parse int right here we don't really ever care about the string version we only want the number version but what happens if we enter something in like parse int of hello we get not a number and if that's the case if you remember from the demo I showed you I wanted to prompt you again to enter in a value that is not a string or that is not invalid unfortunately checking to see if something is not a number it's not as simple as you might think you might think you could do this not a number and just check it something equals not a number this is always going to be false it's a bigger topic I can they go into now it's a very weird quirk in JavaScript but comparing not a number to another not a number will never give you the same they'll never be the same they're always different so we have a method that we can use called number dots is not a number and then we can pass in a value like guess all right so we're asking please enter a number we get a string we turn that into a number but if they entered something that's invalid like hello or a space or whatever we get not a number from parse int so then here we can check if number dot is not a number of guests let's do it whoops let's do the same thing and update guests let's do it again okay so let's try that enter a number I'll enter in I don't know lol it says enter a number again but it's still only going to run one time and that could be problematic if I entered something like lol and then it asked me again to do it and this time I do lol again now guess is still not a number so I'm going to want to loop I want to continue to loop while this is true while number is not a number so while your guests is not a number I'm going to get a new guess and I'll change this to be please enter a valid number all right so now this should keep going as long as I enter something that is not a number and then if I do like nine we're good to go all right so now we need to implement the basic logic of the game where we're going to check if your guess is equal to some target number that we've defined notice I used Const here this is not going to change in a given game guess is going to change we've already seen that so I used LUT so we basically want to check if your guess is equal to the target number but we don't want to do it one time we want to continuously do it as long as they're not equal to one another so we're gonna have another while loop and in fact I'm just gonna comment this out for a moment and just write our basic while loop while guess is not equal to the target number we're going to ask for a new guess and if you remember what I showed you earlier we also get some we give the user some feedback it says your guess is too high or your guess is too low so we could do something in here like if guess is greater than target num will console dot log and I'll do a string template literal that just shows the guess here is too high so if your guess is greater than the target well print whatever nine is too high else we'll do the same thing except too low guess is too low all right so that's gonna give some feedback but we're gonna have an infinite loop if I run this right away because I need to make sure we're getting a new guess every time through this loop and checking that each time so I'm going to call this again please guess again enter a number sure let's do please guess again all right so we've got our while loop we start with our target num and with guess and then wild guess is not the same as target num we give some feedback too high or too low and then we get a new guess and if it's not correct this process starts over it runs over and over and over until guess is the same as target numb at which point we could do something like alerts you win sure let's see what happens here refresh the page enter a number let's go with nine nine is too high please guess again one one is too low two three four five six and we won okay so on the surface it may appear to be working but we don't have this error handling it's not even error handling but we don't have this type checking here we got rid of that but what we want to do is make sure that we have that and I've added it back in but it's really only going to work the very first time you make it guess so if i refresh the page again let me finish this come on okay here we go so if i refresh the page again I'll enter a invalid number it is gold to me it asked me to enter a valid one but now every other time it's just saying not a number is too low not a number is too low this logic went away I want that to come back in there I want to make sure that we're still checking to see if you're actually entering a number so what I'm going to do is take this law and also include it after you make a guess while that guess is not a number we're gonna keep guessing and that should do the trick for us let's see 1 9 I'll enter something invalid please enter a valid number it's gonna keep waiting and waiting for me to enter something valid until I do so now we have our basic logic our code is kind of ugly and I would like to clean it up using functions so that's what I'm gonna do I'm just gonna make a couple of functions and move this code into them so the first thing I'll do is just take this entire thing and put it in a function called probably start game and the only reason I'm doing that is just to I don't know make things a little bit easier to understand and then instead of start game I think I'm gonna do I want to keep this here yeah I think I'll just keep that there I might make a function just call just for practice here called Jen generate random or something you really don't need it but just to get practice down here I'll define generate random and we'll return math dot floor blah blah blah blah blah okay but then we have some seriously duplicated codes this right here making a guess or asking for a guess making sure it's not not a number over and over and over and then the same thing here so what I think I would do is actually make a function called I don't know get input and get input is going to prompt to enter a number okay and parse that int so I'll just steal that from here and save that to a variable let guess and then we're going to continue to check while that guess is not a number same thing we've already done please enter a valid number all right and then at the end we're just going to return guess so if we made it to this point this function it means that your guests is a valid number it's not not a number okay now I can actually replace all of this I don't need this here anymore let guess equal get input and that's it I've moved that logic over there and I can also do the same thing here guess equals get rid of all that get input again so let's verify that it works so far and I haven't messed anything up I will need to execute start game I'll just do that here at the bottom refresh the page enter a number one one is too low let's try and drink something an invalid please enter a valid number so the same logic it's just been moved around so nine is too high three i won alright and I think that's pretty much all that will do for now we could move this into its own function this logic to display whether your guess is too high or too low honestly though it's not really something that I I wouldn't do it's just a couple of lines here that we'd be saving it would be nice if we displayed something other than you win maybe how many guesses it took so that would be something definitely worth adding in you know you you guessed correctly on your first try or took ten tries or whatever also other things you could do is make it harder so ask a user at the beginning how hard they wanted to be how many what the range is from one to ten or one to fifty or one to 100 also give the user the ability to quit at any points because right now if I start it over I have no way of getting out of this if I want to finish I can click cancel but it's just gonna keep yelling at me so maybe you could check to see if a user enters queue or quit and you could stop the loop which is actually not something we've covered you need to use a keyword called break another thing that you could do if you wanted to add on to this is give the the user the ability to replay or to start over once they win so there's a lot of things here that you could add in but honestly I just wanted to do something slightly more complex than what we'd seen so far nothing crazy and like I've said before it takes time it takes practice and and there's a lot more to JavaScript than what we've covered there's no way even in a couple of hours on YouTube there's just no way that I can I can show you everything that you need I'm a broken record but you know my JavaScript courses are like 40 hours because there's just a lot to talk about alright thanks for watching everyone I hope you endured and then maybe enjoyed this I know it's long trust me it's long for me too alright it's a lot of work please consider subscribing liking this video sharing it with anyone who you think might be interested in learning JavaScript especially if anyone has some spare time these days maybe it's C it's a good thing to learn and again this video is sponsored by me my online software engineering bootcamp it comes with a job guarantee if you are serious about continuing to learn JavaScript and other things like react and Python and sequel and databases and get and github in terminal and all these skills and you want to leave with a nice portfolio of projects take a look again you're paired with a mentor one on one you meet every week you can take this at your own pace finish it in six months or two weekends and weeknights I finish it nine months you get mock interviews career support and if you don't get a job then you don't pay anything so pretty low risk anyway take a look ends thank you again for watching I hope you're all doing well and that's pretty much it for me well alright goodbye
Info
Channel: Colt Steele
Views: 68,964
Rating: 4.9722323 out of 5
Keywords:
Id: x2RNw4M6cME
Channel Id: undefined
Length: 166min 9sec (9969 seconds)
Published: Thu May 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.