Loading
Lesson 28
Courses / JavaScript for Complete Beginners
Using “else” to Deal with False if Condition in JavaScript

Video Transcript

Welcome to NVK Tech World. Let's continue. We're now going to learn about the else block. Picking up from the previous example right here. So if the age is greater than or equal to 18, you're going to print out a message saying that you may enter. Now what if you're not over or at least 18. We want to display a message that you cannot enter. So to do that we're going to do the else block. So right after the if, we can add an else block. So I'm going to type else, open some curly braces, a code block, add some indentation because there's a new code block. I'm going to usually add two spaces. I'm going to print out a message saying you are under 18. Sorry, but you cannot enter. So what's going to happen is if this condition in the if clause right here is false, it's going to go here and execute those blocks. If the condition is false, it goes to the else block and executes all the statements there. I'd like style convention add the else right here under the closing brace of the if. Some people like doing like this. It doesn't matter. Choose your own preferred style. Okay. So let's try it out. Remember age is 16, as I said before. Let's try it out. So I executed this guy. And then I got the following message you are under 18. Sorry, but you cannot enter. Okay, so that's the else block getting executed because the condition was false. Now let's change the age. Let's put it at 18. Age is now 18. Let's try the same thing again. I'll help Aero to go reference my previous statements and execute it again. Now I get the message you are at least 18 years old, you may enter. And that is because as if we analyze the code right here, age holds the number 18. 18 is greater than or equal to 18. This becomes true because the condition in the if statement parentheses here, is A is true. What gets executed is whatever is mentioned in the block for the if statement. And it skips everything else. Okay, this guy, this part does not get executed because the condition here is true. Therefore, only this part gets executed. Everything else as part of the if else statement is skipped. This guy does not get executed. Okay. So that's it for this lesson. We learn about the else part of the if statement. If the condition is true, it executes the code block defined by the curly braces right after the if. If the condition is false, it goes to the else block. Okay, and everything there in the else is executed. Remember, if the condition is true for the if statement, only the part here, only the code block right after the if line is executed. Everything else in the else block, for example, is skipped. So, see you on the next lesson.
No comments yet (loading...)
No comments yet (loading...)
Did you like the lesson? 😆👍
Consider a donation to support our work: