This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by CGrahamS
over 9 years

"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

1 vote

Permalink

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…

points
Submitted by Isi Azu
over 9 years

Answer 5269c1a6abf8214710001b91

0 votes

Permalink

That did help! Thank you!

points
Submitted by CGrahamS
over 9 years