- Read Tutorial
- Watch Guide Video
- Complete the Exercise
Now that you have a basic idea on the syntax for using conditionals
and also a good idea on the full list of the comparison operators
.
Let's talk about how we can give our programs more of a dynamic type of behavior. So far we've just talked about implementing if statements
an if statement isn't too handy without also having the ability to give another option. The ability to have an if or an else, I love the way that they're described because you can read it almost like plain language. Where you can say if such and such is true. If this condition is met I want you to run everything inside of this section. Else, if not then I want you to show everything or run everything in this other section.
Let's go through an example. I'm going to say var age is equal to 30. Now if I say age is less than or equal to 10 then we'll console log. "You can eat from the kids' menu".
var age = 30; if (age <= 10) { console.log('You can eat from the kid menu'); }
Right now if we run this, nothing is going to happen because this is not going to look in this condition and find a true statement. Remember the way that conditionals work is they check to see if a certain kind of condition is true or not. In this case, the condition is age being less than or equal to 10.
What javascript does, is it comes in here and it looks inside of these parentheses and it says, that is not true so I'm going to ignore everything inside of here. Everything from the curly bracket down I'm going to ignore and that's fine, in certain situations. There are many times where I use just an if statement just by itself.
However, in this situation and in many other situations you want to have some other kind of condition you want to have, this is what I want you to do if the conditional is true but I may want you to do something else if it's false. Here what we can say is just Else
right after the curly brackets and then here we'll console log just copy up and instead of saying "you can eat from the kids' menu" say "adult menu time for you".
if (age <= 10) { console.log('You can eat from the kid menu'); } else { console.log('Adult menu time for you'); }
Now if I run this is going to go through and it's going to skip over the first condition right here, it's going to skip over everything inside the curly brackets, because this is not true. So because that's not true. It skips down to the else and then it's going to run everything inside of the last brackets. Now if I change the age to be 8, then hit run again.
Now you can see it says "You can eat from the kids' menu".
So that is how you can implement a basic IF ELSE
condition inside of javascript.
In the next guide, we're going to go through how we can add more complexity here and how we can set up a full set of scenarios for our conditions.
var age = 30; if (age <= 10) { console.log('You can eat from the kid menu'); } else { console.log('Adult menu time for you'); }