+ 1
What's the point of "else-if" statements? Couldn't one just write more follow-up if statements?
For example: if (a > b) {max = a;} else if (a < b) {max = b;} else {document.write("no max");} The above is the same as the following: if (a>b) {max = a;} if (a < b) {max = b;} else {document.write("no max");} So why would one ever need else if?
4 Answers
+ 5
The two things you postet are not the same.
If the first if is evaluetad to true, the following else if and else statement isnt even evaluated.
In the second example you posted both if statments are evaluated even if the first if would be true.
So in the end the first example is a few cpu cycles faster.
+ 1
To avoid double true cases, you never know what the input's gonna be :) Also they are just looking better and make the code look more readable.
+ 1
Great answer Dragonxiv! If/elseif also lets you group things together, so for example you can provide all the different reactions you want to an input follwed by an 'else' that catches anything you missed/didn't expect.
0
Dragonxiv ohh you're totally right. Forgot about that. Thanks! :)