+ 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?

9th May 2019, 6:53 AM
Isaac Svi
Isaac Svi - avatar
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.
9th May 2019, 7:09 AM
Dragonxiv
Dragonxiv - avatar
+ 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.
9th May 2019, 6:57 AM
inxanedev!
inxanedev! - avatar
+ 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.
9th May 2019, 7:20 AM
Rincewind
Rincewind - avatar
0
Dragonxiv ohh you're totally right. Forgot about that. Thanks! :)
9th May 2019, 7:13 AM
Isaac Svi
Isaac Svi - avatar