Modern JavaScript Tutorial #3 - Control Flow
Skills:
JavaScript Fundamentals90%
Key Takeaways
Control Flow in Modern JavaScript using for loops, while loops, if statements, else if statements, and switches
Full Transcript
okay then gang so as we start to write more complex programs there's gonna be points in our code that we need to either make some kind of decision on what to do next or maybe execute a piece of code over and over and over we want to somehow control the flow of our code for example if we have an array of data for example this array of names right here that we want to maybe cycle through and perform some code on each element inside that array then we would use what's known as a loop a loop is a type of control flowing JavaScript okay likewise at some point we might also want to check if a certain condition is met for example is a user logged in or is a score over 100 and then only run some code when that condition is true and this is known as a conditional statement so these two different concepts of looping and conditionals they are collectively known as control flow in JavaScript because we're using them to control the flow of our code or application whether that be using a loop to repeat a section of code or to conditionally run a section of code based on a certain condition they're really important parts of the language and we're going to be using variations of them quite a lot as we go through the course and make different projects so we'll be talking about these concepts and looking at the different kinds of loops and conditionals for the rest of this chapter okay then my friends saw the first type of control flow that I want to talk about loops and in particular we're going to talk about one type of loop now there's many different types of loops in JavaScript I do think it best that we just focus on one of these a for loop to begin with then we'll talk about the rest of them later on so I'm gonna write out this for loop first of all then after I've written the loop I'm going to explain it and show you how it works so I'm saying let I equals 0 then a semicolon then I is less than 5 semicolon then I plus plus then we open and close some curly braces like that at the end now we don't add a semicolon at the end of these curly braces we don't do that for loops all right now remember at the end of the day the job of a loop is to look through a portion of code over and over and over a set number of times that's what they're there to do so keep that in mind when we go through this so first of all this thing here when we open the curly braces and we close the curly braces that is what is known as a code block it's just a section of code that we're kind of sectioning off and it's for this loop okay now that we create the followed by first of all saying the for keyword then we have some parentheses and inside the parentheses we have three different things the first thing right here this is an initialization variable so we're saying to begin with we're going to create this variable I and set it equal to zero now this variable is a bit like a counter and it keeps track of how many times we cycle through the loop and how many times we run the code inside the loop then the second thing is a condition this is going to evaluate to either true or false if this condition is true then we're going to execute the code that's inside this code block if it's false then we're not going the third thing over here this is a final expression and this is going to execute every time at the end of the code block okay so every time we loop through some code at the end we're going to take I and add one to it so let's run through this the code reaches the for loop and we set I equal to zero to begin with and then we check this condition is I less than five well yes it is because it's currently zero so then we execute some kind of code that's inside this code block we've not got any there yet but later we will then once we've executed that code we come up to this final expression we take I which is currently 0 and we add 1 to it so now that's seen okay we've been through here once essentially so we come back up to the top we don't re initialize the variable we just keep I as 1 because we've just added 1 to it and we recheck the condition is I still less than 5 well it's 1 so yes it still is less than 5 so we execute the code block again and at the end we do this final expression we add 1 to I and now it becomes 2 then we go back to the top - less than five yes it is so we do the code block and it loops and loops and loops until eventually I is five it's no longer less than five so then we don't execute the code inside the code block anymore we've already looped through it enough times based on this condition so we don't do it again then once we've done it we come out of the loop and we carry on down the file with the rest of the code okay so then let's see this in action I'm gonna see inside here console dot log and we're gonna say in loop colon and then we'll also log a second thing to the console which is I so remember I is zero to begin with then every time we go through the loop it's going to add one to I so we should see zero to four we won't see five because at the point when I is five it's not less than five anymore and it doesn't execute the code in here anymore at the end of it I'm also going to do another console log and i'll say loop finished so this is only gonna run once we've looped through this x amount of times so save it and preview of a hill and we can see in loop 0 1 2 3 4 then we break out of the loop because i is not less than 5 anymore and final it will log this to the console so i hope that makes sense now a lot of the times we might not know how many times we want to loop through something we're not just gonna pluck a number from thin air and say okay I'm gonna loop through you ten times no we don't do that typically what we do is loop through data of some kind so we could get for example a list of users or names from a database we don't know how many people are in that list or array of names and we want to cycle through them and we want to perform a for loop for example for each name in that array and do something with that name so let me comment this junk out and come down here and what we're gonna do is create a constant now we're not going to grab these names from a database because we've not touched that yet but what we will do is just create an array and imagine that we've got these from a database okay so the first name is going to be Shawn then I'll say Muriel and then Luigi okay so now we have our array of names and we need to give this comest a name so we'll call it names and now I'd like to cycle through this array using a for loop okay now remember I said we might not know how many elements are inside here we know it because we can just look at it and say well there's three inside there so we know how many times we want to cycle through it but just suspend disbelief for a minute and imagine we got this from a database and you don't know how many names are inside here if we need another way to tackle this so the way we do it is by saying for first of all we still initialize a variable to be 0 to begin with that's our counter then we say for I less than names dot length so that's going to take the length of this which is 3 and it's gonna say for as long as I is less than that value then we're going to cycle through it and that ensures that we're going to cycle through each one does that make sense cool so finally we take I and we plus plus to add one at the end of every loop okay so inside here I'm just gonna console dot log I to begin with now we should know what happens here it's gonna be 0 then 1 then 2 and then that's it ok because when it gets to 3 the length is 3 and it's no longer less than that so then I don't just want to log out I know I want to log out the name that we cycle over each time okay so first Sean then Mario then Luigi how do I do that because this is not automatically linked to this all we're doing is using the length property at the minute what we want to do is every time we go through this loop log out the names in order so what we could do is we could take the names and we could use square bracket notation to get each element and what I'm gonna pass in here is I now I to begin with on the first loop is going to be 0 because that's what we initialize it to be so when we first execute this code is 0 and it's going to log out Sean then we add 1 to I and come back to the top when we run this code block again I will now be 1 so we'll get this element and log that to the con and so forth so if we save this now and preview we can see all of these names so that's cool right we can now cycle through an array of any length we don't have to know that length using this kind of syntax now a banchon instead of just a login this to the console we wanted to do something like create a little snippet of HTML a little template for each name so that eventually we're going to output that to the browser well we could do something like this let HTML equal to a template string which is backticks remember and inside that template string we could just write some HTML I'll do a div tag and close that off then what we want to do is output the variable this thing names I inside this div each time so remember to output a variable inside a template string we use dollar then the variable name inside the curly braces and we want names and then I so that's going to be shown first and Mario then Luigi okay so then let's log to the console the HTML each time around so save that view in a browser and we can see we have a little template now for each individual name awesome so there one more thing before we close up just a little bit of terminology you might hear me and other developers in the future talk about cycling through an array or some data as iteration and each iteration is one cycle through so every time we perform a code block that is one iteration through the data okay so that was just a bit of terminology that is all we're just cycling through the data is the same thing some are friends that is a for loop in the next video and with a shift our focus to another type of loop called a while loop which is similar but just a bit of different syntax okay then so in the last video we saw how to create a for loop now in this video I want to talk about a different type of loop called a while loop now they do exactly the same thing they loop through some code a certain amount of times there's no real difference the only difference is the syntax how we write them so this was our for loop from the last video we had three things inside here and initialization then we had a condition then we had a final expression where we incremented I each time around so if we run this we should see I go up to 4 from 0 and we did so what we're gonna do is change this into a while loop so first of all we change 4 into while then we don't have all three of these different statements inside the parentheses we only have one of these statements inside the parentheses and that is the condition itself so right here we're saying while I is less than 5 I want you to run this code inside the code block now there's a couple of problems with this first problem is that we don't even know what is nowhere in this file do we initialize I before when we use the for loop we did it inside the parentheses but we don't do that in a while loop I must already exist somewhere so we say let I equal to 0 before the actual loop begins we declare that outside of the loop now I'm not going to run this because if I do it's going to be a big problem we're going to get stuck in what's known as an infinite loop so why is it an infinite loop well think about it we're saying that I is equal to 0 to begin with then we're coming to this loop and we say while I is less than 5 then execute this code well it is less than 5 is 0 so it does this code then we're not incrementing I anyway we're not adding 1 so it's just gonna come up again and say is I less than 5 well yeah it's still 0 so we're gonna run it again and over and over and over and over until eventually your browser will probably crash because we're outputting it so many times because I is never changing that is an infinite loop and it's a really bad thing so what we need to do before we run this is find a way to increment i every time around now before when we used to follow up we did that inside the parentheses but again we don't do it here in a while loop we do it inside the code block so we could do it at the very end right here so we run the code and then at the end of the code block we say take I and add 1 to it then when it comes to the top again it's going to say well I is 1 now still less than five but eventually I will get to five and then it won't run so we're not caught in an infinite loop okay so if I save this again I'm going to go over to the browser and now we can see exactly the same result so this works so this is just a different way of creating a loop using a while loop instead of a four loop okay so before we did an example with some data some names so what I'm going to do is also create a constant here called names and set those equal to an array we'll put inside Shawn Mario and Luigi okay so we have those names and we want to do the same thing now I'm going to comment this stuff out I want to cycle through those names using a while loop so what I'm going to do is again say let's I equal to zero we still need that initialization variable then I'm gonna say while I is less the names dot length I want to do something and inside here what do I want to do I just want to log out the name so I'll say console dot log and then in parentheses the names and then we'll pass I and square brackets to get that position from the names array now we need a way to increment I otherwise we're going to get stuck in an infinite loop so we'll say I plus plus at the end and this is going to do the same thing as the followed before it's going to cycle through these and it's going to output the name each time around so save it and preview and boom we get those names okay so there we go that is a while loop just an alternative to a for loop so then just a quick video about do-while loops which is really just an extension of the while loop up here so we've seen that we can do a while loop where we evaluate some kind of condition and if that is true we run the code and then we add one to whatever the counter is now imagine that we start off with I equal to 5 then this thing right here this is never going to be true and we're never going to run this code now that might be fine but sometimes you want the code to run at least once even if this condition is not true okay so even if I starts at 5 it would be nice to maybe run the code once and then we don't execute the loop more okay because the condition is not true so how do we do that well we'd use a do-while loop which like I said is just an extension of the while loop we just write a bit different so I'm gonna take all this code here the code block and cut it and then above while I'm going to say do and then I'm going to paste the code block and now what we're saying right here is do this code and it's going to do it once to begin with regardless of the condition being true or false in here and then at the end of the do block we have our wild keyword and then we do add a semicolon at the end because it's not a code block at the end anymore we don't add them when it's a code block at the end but now it's the wire statement we do add our semicolon so again we're saying let a equal 5 then we come down here we do this code block regardless and we still add 1 to I then we run a while condition and if I is less than 5 again then we go back up to the loop and run it again and we carry on as normal but all this does is really wants to begin with even if the condition is not true in here so let me save this and preview in a browser and we can see the value of I is 5 so that is because we run this once and I is 5 if we change this to 4 then save it it's still only going to run once because we run it and I use 4 then we add 1 to 4 which is 5 then we evaluate the condition well I is 5 now so it's not less than 5 so we don't run it again if I is 3 then we should get it twice we get 3 and 4 okay so that's an easy way to execute a block of code inside a loop first regardless of whether the condition is true or false okay then so we've seen how we can use loops to execute a block of code a certain number of times based on a certain condition now the other type of control flow is conditional statements also known as Eve statements and the cop if statements because we say if a certain condition is true then we do something so we check a condition and we only execute a code block if that condition is true now this time we don't use any kind of counter variables because we only ever execute the code block once on not at all we don't loop over the same code multiple times like we did in loops so let's do an example I'm going to create a contest called age and set that to be 20 to begin with now I'm going to do a conditional check an if statement and to do that we say if then in parentheses we do our condition what do we want to evaluate well we want to say if the age is over 20 then we have a code block at the end where we want to do something inside and this code block is only going to execute if this condition is true so inside here we'll just say console dot log and then you are over 20 years old ok so if we save this and preview it in the browser then we don't see anything and we don't see anything because this is not true age is not over 20 ages equal to 20 so if I change age now to 25 then this should evaluate to be true and now we can see you are over 20 years old okay so that there is an if statement now we can also do if statements with data so to check if we have certain amount of items in an array or something like that so I'll create a new constant and I'm going to call this ninja's and set this equal to an array and inside I'll do a few different strings so we have shown and then we can have Rio then translate and then finally Yoshi so we have four names in there now what I want to do is say if ninja's dot length is over three then we'll execute some code so it's going to grab the length of this which is four is it over three well yes it is therefore this evaluates to true and we can execute this code so inside we're just going to log a message and this time I'm going to use double quotes and I'll tell you why in a second I'm just going to say that's a lot of ninjas now normally when I do strings are use single quotes but I double quotes because there's a single quote inside the string right there so if I used a single quote to do the entire string then you'll notice that the string is actually closed here so it's no longer used as an apostrophe but to close the string instead we don't want that where you want to use double quotes so that this single quote here does not close the string okay so anyway let's save that and run it and we should see that in the console now if I change this to be something like four then the length is not greater than four and we don't see that statement so these are I suppose silly examples of why we'd use an if statement maybe we'd do something like this to check the length of some data but typically we want to do something more useful like we want to check if a user is logged in if they are we'd do something or if they're signing up is the password that they provided us with eight characters long because if it's not we want to send back an arrow and say improve your password or something like that so what I'm going to do now is a very simple example Const plus word and set it equal to a string and the password that a user types in is going to be plus now that's a weak password so what we're going to do is check if that password they enter is at least eight characters long so I'm going to say if password dot length and we can do this on strings remember to get back the length of the string and we're going to say if that is greater to or equal eight characters long then we're going to lock something to the console inside will say that password is long enough if it's not at least eight characters long then it's not going to run this code so if we save it we can see it's not run this code but if I change this now to something like password like this we can see this is now eight characters long and this should run so if I save it preview we can see that password is long enough now sometimes we might want to feed back some information if this code doesn't execute for example if it was this again and it was just four characters long and we saved it we don't get any feedback whatsoever it might be that we want to say that password is not long enough and to do that we're going to have to talk about else statements so we'll do that in the next lecture southern gang currently we're checking if a password is at least 8 characters long now if it is then it's going to run this code block and output this if it's not if this is false for example if this is 4 5 6 or 7 or something like that characters long then it doesn't run this code block now it would be good to run a different code block if that condition right here is not met so we can offer some feedback to the user something like the password is not long enough now to do that we use an else statement so at the end of the first code block after the if check we can say else then open up a new code block and fire this if that first condition is not true so he checks this if it's true it fires this code block and not this if it's not true then it doesn't fire this code block but it does fire this instead this is the else Clause okay so what we could say is console.log and then say password is not long enough alright so save that and since this is currently four characters long it should be the else code block the fires and not this one so let's check that over here password is not long enough and notice it's only ever going to run either one of these code blocks either this or this never both of them okay if this is true it only runs this and it ignores the else case if this is false it only runs this and ignores this case now sometimes we might want to check multiple different conditions so say for example we still want to check the password but we want to check first of all is the password at least 12 characters long if it is then we'll output a message that says this password is super strong or mighty strong or something like that if it's not then we'll do another check is the password at least eight characters long if it is we'll output this if it's not then we'll catch it right here and run the else statement so again only one code block will ever but this time we're going to check multiple different conditions so how do we do that well let's start at the top we're going to check first of all if the password dot length is greater than or equal to 12 characters long if this is the case then we're going to console dot log that password is very strong okay so that's the first condition now we also want to check the second condition but we only want to check this if this is false so we can't just leave it here because if it's 12 characters long currently then it's going to run this and output this then it's going to come down here and it's going to run this as well we don't want that we want one or the other so instead of creating a new if case we instead bring this back up and do else if okay so we say if this is true run this if it's not then go down to the next Clause else if and another condition if this is true we run this if it's not true we go to the else class and we run this instead so again it's only ever running one of them and we can chain as many of these else ifs on as we want we could have another if we want we could do else if here and then else if again we're not going to do that because it's just going to get messy but the idea is there but can chain them together if we want them so let's run this I'm going to change this to something like password 1 2 3 4 which is 12 characters long so hopefully we get this right here so save it preview and we see that that password is might strong should be mighty ok and if we change this back to 8 then the first condition should fail this should be false but this should be true so save it and we can see that password is long enough if we change it to 4 then it's going to go right down to the else clause and just run this password is not long enough all right so there we go that's how we use else statements and also else if statements to check multiple different conditions now then so far we've looked at several different exam of satisfying conditions of running code if that condition is satisfied now what if we want to satisfy a combination of different conditions all at once in one set of brackets because it the minute we're just looking at one condition is the password length over X amount of characters if we want to satisfy a combination of different conditions inside the same check then we can use what's known as logical operators and two of the main types are logical or which looks like two pipes and logical and which looks like two am persons so let's think about this imagine we want only this to run if the password length is at least 12 characters but also includes an @ symbol so what we do is we place our logical and because we're checking two conditions we want both of them to be true we want the password length to be at least 12 and we also want it to include the @ symbol so we're going to say and using logical and password dots includes we've seen this method before this is the way we can check if something includes a certain character and we're looking for the @ symbol so that is checking both of these conditions at the same time if both of them are true if it's at least 12 and includes this then the whole thing will evaluate to true and this will fire if one of them is not true so say for example it is at least 12 but it doesn't include this then the whole thing will fail it would be false and it won't fire they both need to be true for this to work for this to be satisfied this condition okay so let me change this to something that's 12 characters long 1 2 3 4 and it includes this in fact we'll take that off for now and just do this save it and we can see that password is long enough so even though is 12 characters it doesn't include this so this is not true and it goes to the next else if while the password is at least 8 characters so it runs this so them if we now place in the outside then should pass this first check because now both are true if we save it and we can see that password is mighty strong okay cool so that's using the logical and operator which is double ampersand that's how we check two different conditions and you could add a third one if you wanted to I'll tell that would get a bit messy now then let's have a look at all so say for this second if check down here we want to say well fire this code block if the password length is at least eight or and it's double pipe and the pipes are next to the spacebar on most keyboards you probably have to press shift and that key so we're saying if password length is at least eight characters or if the password dots includes the @ symbol then we're going to find this code block so even if this is four characters long so it's not at least eight then because we've said all only one of these conditions has to be true and because it includes the @ symbol over here and this is true then this is fired okay so if we save it and preview we can see that password is long enough maybe this should be changed to strong enough and this should be strong okay so when we use the or operator only one of the conditions has to be true so we could change this to be password and it's eight characters long but it's not this this is false but this is true this was still passed because we're using all and only one of them has to be true and we can see that password is strong enough now if we wanted to we could get really ambitious and try something like this we could chain on an and over here and say password dot length is over five okay so what we're doing here is this is one condition and this is one condition because we've got an or in between them but this one condition over here is comprised of two different conditions and both of those have to be true for this side of the or to work or to pass right so if it includes an @ symbol and it's at least five characters in length then this side will pass so if we change this back to for and we put an @ symbol and we need to change this right here to greater than or equal to if we save that now then it's not going to pass because it's not at least five characters long it has the @ symbol but this one doesn't pass if we change it to one two for example then save it then it does pass okay so there we go that is the logical or double pipe and the logical end and we can add these into our if checks to check a combination of different conditions okay then so far we've looked at a few different conditions and we've executed code only if those conditions are true but sometimes we want to execute code only if a condition is false so normally when we do an if check we do if then some condition right here and we run the code block if that condition is true that's the way an if statement works if whatever is inside here when it's evaluated is true then this code block is going to run okay now imagine we have a user variable and when it's false it means they're not locked in now I want to make an inch at which is going to run some code with the code block only when the user is false now I can't put in here every user like that and then run some code because this is only going to run when user is true and I want it to run when user is false so how do I do that well to get around it we use what's known as the logical knot which looks like an exclamation mark so when we place an exclamation mark in front of a boolean so something that's either true or something that's false what it does is reverse that boolean so if I put it in front of a true value then it's going to evaluate to false if I put it in front of a false value it's going to evaluate to true so let me demo this I'm going to consult log and we're going to console dot log true and we'll duplicate this and consult log false okay now then if I run this we see true and false now what happens if I place Lamesa mark and exclamation mark in front of them well like I said this is logical note and if it's placed in front of true it takes that value and it turned it on its head it makes it false same for this it takes the false value and switches it to true okay so if I save it we should see false first then true and that's what we see false then true so that's how we switch a boolean value so now let's go back to the problem I want this to run if the user is false now normal behavior means that the if statement only runs the code block if whatever is evaluated in here is true now currently it's false but if I place the logical not or the exclamation mark in front of it then it's gonna switch that's a true it's gonna evaluate as true the whole statement bear in mind this doesn't actually change the value of user user will still always be false we just change in the evaluation here we're switching what user is inside these brackets the outcome of the expression so now this whole thing is gonna evaluate to true because this is switching the false value so now we can say something like console.log and inside that you must be logged in to continue and save it and if we run this now we can see this in the console and that's worked because this thing right here this exclamation mark is switching the value of false into true all right then gang so we've explored a lot of different ways to control the flow of our code loops and then conditionals now I briefly want to jump back to loops to explain a couple of key words in JavaScript and those are break and continue so imagine we have an array of scores which we do have right here and we want to loop through them so that's why I've created a for loop I'm saying for then initializing our counter variable to 0 while I is less than the length of scores we're going to continue and then each time around we're incrementing I by 1 so inside this loop all we're doing is logging out the score for each iteration using school and then passing in the counter variable which starts at zero so here then 1 and 2 then 3 etc so if we save and preview then it's gonna look something like this and it logs all the scores out now then what our break and continue well let's imagine if we get to a score of 100 when we're going through this loop when we get to that that is the max score you can get in this game and at that point we want to break out the loop because the rest of the scores after 100 they don't really mean anything because we've already reached the top score so what we do is we'd come down here and we'll say if and scores and then square bracket notation I so the current score we're iterating over if that is equal to 100 so triple equals to 100 then we want to break out a loop before we do that let's log a little message to the console we'll say congrats you got the top score and then what we're going to do is break out of the loop so that basically means if we break out of the loop we're not going to carry on iterating of the last two elements even though I might still be less than the scores length this break keyword means now I just want to break completely from the loop ignore all this stuff at the top and carry on with the rest of the code down here so we're not going to see these two now logged to the console like we did before so let me save it and preview this in a browser and you see when we get to 100 we get this message then we break out of the loop and we don't do any more there's no more iterations so that's what the break keyword does it breaks us out of the loop so what about continue well let's do another example say instead of 100 we now check for a score of 0 now that's a pretty embarrassing skål if you get 0 and we don't necessarily want to log that to the console because it's so embarrassing so what we could do instead is say ok well I want to check if the current score that we're iterating over so scores and then I if that is equal to zero then what I'm gonna do is use the continue keyword and what that means is okay I want you to now ignore the rest of the code inside the code block for this loop but I still want you to continue with the loop itself so I want you to go back up to the top and go to the next iteration increase I by one and go to the next iteration so when the score is zero it's gonna run this it's gonna hit continue ignore all of this code so we don't log it to the console and we don't need to perform this if check either but we go back up to the loop and we go to the next number the next iteration because I is now increased by what so that's what the continue does jumps out of that one particular loop that one iteration and goes back to the top so if we save this now we shouldn't see zero log to the console after 25 we should just see 30 so save it go back to the console and we get 25 then 30 then 100 okay so there we go my friends that is break to break out of the loop completely and continue just to break out of the current loop and go back up to the top and continue with the next iteration so then one last control flow technique to look at and that is switch statements so imagine we have a value I've called this value grade and that is some kind of test grade and it could be many different values it could be a b c d e f etc now I've given it D but it could have been any one of those values now imagine that we want to check what that grade was and output a different message to the user dependent on the grade so we could potentially use an else--if statement like this for each different grade and then output something different in each code block now that's fine but it gets a bit tiresome writing these conditions out over and over again and it starts to look a bit untidy as well now a better way to do this where we're checking multiple possible values of a single variable is to use a switch statement and we do this by typing first of all switch then inside we do our variable which were evaluated that great and then we open up our code blocks now before we carry on let me just delete all this because we don't need to anymore so now we're checking the value of this variable now we're gonna have several different cases what it could be it could be an a it could be a bit could be an F and E so we want to check all of the different cases that it could be and we do that by using the case keyword then whatever that case could be so in the case that it could be a we say the case a and then we do a colon then underneath we indent for readability and we write the code that we want to run if grade is a so I could say something like console dot lock and then say you got an a okay so what I'm gonna do is just grab this and I'm gonna paste it down here a few different times let me just scoot that back over copy let me just paste these in and then I'll make the formatting better so case case in case now we want to check the case is B the second time then C then D then e and then at the end we do a default case by typing in default and then we'll say console dot log and we'll just say not invalid great ok so what's happening well we're checking this variable and we have all of these different cases that it could be now if grade is a is gonna run this code if grady's B is gonna run this code instead if it's see this code etc now we just need to update these messages that we log to the console so let's do B see oops C and then D and E so now then if we run this what's going to happen well hopefully it will see that the grade is D it skips this and this and this then it gets to this it says okay well grade is d so I'm going to run this code so if we save that and preview then we can see you've got addy you've got an e and not a valid grade so it's running this but it's also running this and this now if we change this to a and save then notice it runs a and everything after it so why is it doing that well as soon as it gets to a case that it matches for example C then it's going to run the code but it's also going to run the code in every case after that as well now in order to combat this in each case at the end of it we need to do the break keyword and what that does is run only the code for that case and then it breaks out of the switch statement so let's add this in all of them and down here as well and then finally here now in the default case we don't need to use the break because that is the last one and the default case runs only when this is something that's not covered in any of these cases for example if this was I don't know P or something like that so save it now run it and we see we only get the code inside the case for C now if we change this to something like P we're just gonna get the end default case right here so let's save it and preview not a valid grade so there we go that is a switch statement and these are good for evaluating a variable which could be several different values if you want to react differently in each case just one thing to know switch statements use strict equality to check so for example if I type in 50 for example if it was out of a hundred this grade and we used numbers like this then that is not going to work so if I save this now and come over here we see not and valid grade because it's using strict equality and remember that these triple equals and it takes into consideration the type as well as the actual value so this would have to be a string it's a match so save and now we can see it okay then my friends so throughout this chapter looked at a lot of different control flow techniques and in each one of those different techniques we've seen code blocks like this curly braces and those code blocks are just little sections of code that run when something is true or some condition is met right so now we know what code blocks are one last thing I want to talk about in this chapter is block level scope with variables and by the word scope I mean the area in which a variable value is relevant so I already have this if statement right here what I'm also going to do is create a variable so I'm going to say let age equal to 30 now that if I define a variable using let or Const in the root of the document meaning not inside any code block it's in the root of the document up here then that will have global scope and that means it can be accessed anywhere in the file if I want to use it so it could be accessed inside this code block it could also be accessed outside this code block so let's just down here console.log outside code block just to let us know where this is and then we're gonna output age okay and then we're also going to do the same thing but we're gonna do that inside the code block so let's paste this inside here and I'm gonna say inside first code block and I'll put the age there as well so I'm just showing you this to demonstrate that we can access this variable which has global scope outside of the code block and also inside anywhere in the file because it has that global scope so if I save it we can see that we get that value in both cases okay so that is global scope now I can also change that variable inside here so I could say now age is equal to 40 inside here and that is going to access this global scope variable change it to 40 and then output it here and here so if I save it and preview we can see that now is 40 in both cases because we change it here for first before we out put it anywhere now that what if I try to redefine age outside here so if I say let age equal to 50 so I'm trying to really find the variable again I'm not just trying to over write it by saying age is equal to 50 now I'm trying to completely redefine it by saying let age equal 50 now it's not gonna let me do this it's already been declared and I can't do this because it's in the same scope okay now then what if inside the code block I try to say let H equal 40 well what's going to happen there because I'm trying to redefine it again well if I save it let's preview the results so we see inside the first code block we get 40 for the age and outside the code block 30 so firstly most importantly we don't get an error so we are allowed to do this we're allowed to redefine the variable inside a code block even though it's got the same name now secondly it's only creating age equal 40 inside this code block right here outside age still refers to this but inside age refers to this so what this is doing here is creating a local scope for this variable age inside this code block if I just use age then it refers to the global variable that's already been defined but if I redefine it what it does is recreate this variable but it gives it a local scope now we can only access this version of age inside this code block so let me try something else I'm going to say let name equal to Shaun and what I'm going to do is output age and name here and age and name here well let's see what happens save it on preview and we see Shaun here but we don't see it outside the code block and that's again because we're creating this variable inside the code block we're giving it a local scope meaning the sky this variable is only valid inside this code block because we define it inside here we're not defining it outside here with root level scope or global scope so if we define something in the code block it only has that scope and we can't access it outside of that code block does that make sense okay this is also true for nested code blocks and by that I mean if we had some other eve check in here so we'll just say if true so that it does fire this is a nested code block we have a code block nested in another block now inside this code block what if I try to access H let me console.log first of all and we'll say inside second code block and spell is correctly will output age so what value do you think we're going to get here because we've defined it here but we've also defined it here locally if we save it and preview we can see inside the second code block we get 40 which is the value we defined in here so what it's doing is taking the most recently defined value so the value whose scope is most immediate outside of this code block if this wasn't here then it would take this value I can demo that save it and we can see 30 but because we've redefined it inside this code block and this code block right here is all of here this is the scope of this variable now all of this code block including this stuff in here it means the inside this code block when we use age it gets this value okay then so what if I try to say then let age equal to 50 inside this code block well again we're creating a new variable with local scope but this scope is only valid inside here so we're not overwriting this one right here we're creating a new local one with local scope inside just this code block so if I save it now and preview then we should see 50 inside the second code block okay now so far we've just used let but the same would be true if we used Const so let me just now change all of these to Const I'm just gonna place my cursor in front of all of those and change them all to Const and save it and we're going to see exactly the same results obviously we can't change constants so we couldn't later on say something like age is now equal to 35 because once we define a constant we can't change them but the same rules of scope apply to Const as they do to let variables so this idea of block scope is one of the main advantages of using let in Const instead of the older var keyword because when we make a variable using var in ignores block scope so we could have a variable defined you know down here let's just save our test is equal to hello and we can then access that outside down here so we could say test and that would work so even though it's defined inside this code block it's not given block scope whereas these things are once we create them okay so that is one of the main advantages of using let and const because a lot of the time it's useful to declare a variable that is only used inside a code block it's much better to use latin Const instead of var where possible so this idea of block scope might seem strange at first and even probably could go straight over your head but do watch the video a couple of times over if you struggling just to understand at least the basics of block scope because it will definitely benefit you going forward
Original Description
💻 Get the full Modern JavaScript (novice to ninja) course from Udemy. Discount auto applied:
https://www.thenetninja.co.uk/udemy/modern-javascript
In this modern JavaScript tutorial we'll take a look at different ways to control the flow of our code - for loops, while loops, if statements, else if statements, switches and more.
----------------------------------------
🐱💻 🐱💻 Course Links:
+ Course files - https://github.com/iamshaunjp/modern-javascript
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Net Ninja · Net Ninja · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: JavaScript Fundamentals
View skill →
🎓
Tutor Explanation
DeepCamp AI