Check out a free preview of the full Introduction to JavaScript course:
The "If Statement" Lesson is part of the full, Introduction to JavaScript course featured in this preview video. Here's what you'd learn in this lesson's course:

Brian begins implementing control and equality operators to carry out logic, starting out with an if statement and expression.

Get Unlimited Access Now

Transcript from the "If Statement" Lesson

[00:00:00]
>> Brian Holt: Yes.
>> Speaker 2: Why doesn't it execute the else? If the first part is true, why does it just ignore it?
>> Brian Holt: So-
>> Speaker 2: You know what I mean? Instead of running each line of code one after another?
>> Brian Holt: That's because we're doing this if statement, right? So that's what these if statements are for.

[00:00:21]
It's like I only wanna execute one of these two things based on some condition, right? So in this particular case, this is a dumb condition, right? But maybe here, it would be like const areTheLightsOn =, and let's say they are for now, right? And this would be defined somewhere else.

[00:00:44]
And someone says, areTheLightsOn, then you would do something like here. Turn the lights off, and this would have some sort of code that would be doing that, right? And then turn the lights on, right? These are comments, by the way. This is just how you leave notes for yourself in the future.

[00:01:05]
So this allows you to kind of branch into different paths of logic, depending on what's happening, right, depending on the ambient variables. Does that answer your question?
>> Speaker 2: I think so.
>> Brian Holt: It's just based on this condition, run this code. If this is true, then do this. If it's false, then do that.

[00:01:25]
>> Speaker 2: What if someone made the condition where both are true, the if and the else? Would it still stop at the first part, not from the else?
>> Brian Holt: So they can't both be true. It's like areTheLightsOn is either gonna be true and false and there's no middle ground.

[00:01:43]
It's black or it's white, right? Does that answer your question?
>> Speaker 2: Yeah.
>> Brian Holt: Okay.
>> Speaker 3: I mean, you could write code where there are multiple conditions, if maybe not lights are on, but if 2 plus 2 equals 4, do this. But if 2 plus 3 equals 5, do this.

[00:02:00]
And then it wouldn't get to the second statement, right?
>> Brian Holt: Correct, so in fact, my next thing is on else if, so hold your thought. [LAUGH] But you're correct.
>> Brian Holt: Suffice to say, only one of these blocks will ever be executed, and you can just depend on that fact.

[00:02:20]
One of these is always going to be executed. Exactly one of these is always going to be executed, unless there's no else, right? So if I take the else away here, this may or may not happen, right? And if this is false, then it just skips this and goes on its merry way.

[00:02:39]
>> Brian Holt: But if you have an else, one of them will definitely be executed.