if, else, and else if
To make an "if" statement you must start out with an "if" obviously. To get a better comprehension, I will give you an example first then we will break it up into pieces. EXAMPLE:
if(1<2){alert("1 is less than 2");}else{alert("1 is greater than 2.");}
It doesn't seem too organized and quiet frankly, just messy. So we're going to organize it a bit and make it more understandable to our programming:
if(1>2){
alert("1 is less than 2.");
}
else if(1=2){
alert("1 is equal to 2");
}
else{
alert("1 is greater than 2.");
}
If you understand that; that's great! If you don't, that's okay, no one blames you, I will show you what it means:
1st Part: if(1<2)
Okay, so this basically means, "if 1 is less than 2...", which of course it obviously is. So what happens now?
Well that's where these squiggly brackets come in.
2nd Part: { }
These brackets are called "curly brackets", and with these you're saying: "Okay, now we know that 1 is less than 2, now do something...". When you call an "if" statement, the computer tries to find out if it's true or false. If it's true; it does what is inside the curly brackets, if it's false it just skips it and moves on. And that is where the else if and else come in.
3rd Part: else if
In this part, you're saying, "Okay, so the first 'if' statement was false, so go to this one and see if this one is true or false". The 'else if' statement is like a normal 'if' statement, expect it only gets called in to action if the 'if' statement before it is false. And from there, it just has the same properties as the 'if' statement. If this one is false too, it will go to the next else if, and if that one is false, then it goes to the next, basically you can put 'else if' statements as much as you like. But if you want a default action where all the ones who are false or get rejected go to, than you are gonna need an 'else' statement.
4th Part: else
This is like the most simplest part of the whole 'if' mess... It doesn't include any parentheses at all only the word 'else', a couple of curly brackets, and what action it does. This is where all the statements that were rejected by 'if' statements, and 'else if' statements go to. It doesn't have any standards or rules in this place. It's public.
Here is a little story explaining the 'if', 'else if', and 'else'.
One day, a number one was feeling like he wanted to go to a club, he tried to go to the 'if' club, but they didn't except him, you needed to be more than 3. Then he went to the 'else if' club, but you needed to be more than 2. He tried every other 'else if'' club in town, but none excepted him. He finally reached a club called 'else', they didn't have no rules, no policies, no anything that would keep him from entering. He was happy to see other rejected numbers there too, he didn't seem so alone any more. THE END.
I hope this helped. - Rick "Rixel" (TekBird)
No comments:
Post a Comment