This forum is now read-only. Please use our new forums! Go to forums
"If" statement without the "else"
As I was going through this section I was confused. In the main text of this section you mention if/else statements but never mention that “if statements” can exist without their “else” counterparts…or at least my code worked like that. Why?
Answer 526897a4abf821c5f4002967
An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.
eg
if (I am hungry) {
go and find food
}
On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.
e.g
if (I am hungry){
go and find food
}
else{
continue working
}
The last thing you should know about is the if / else if statement, which you use if you require more than two different codes to run depending on whatever parameters you set. you can continue to loop through (if, else if.., else if.. else if.. else if………..) until you have satisfied all the different parameters. If you place an else at the end of that, it will execute only if all others have failed.
e.g
if (I am hungry){
go and find food
}
else if (I am tired){
take a nap
}
else if (I need to pee){
find the bathroom
}
else if (I am bored){
take a break
}
else{
continue working
}
That’s the way I understand it, I hope that helps…
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency