Forum Moderators: open
After finding a true statement, does the browser then skip over the remaining "else if" statements without analyzing them and therefore run faster?
If not, the additional text would just makes the code load slower.
Thanks, Peter
and therefore run faster?
Either way, it really isn't important with any computer sold within the last decade, since your code probably isn't going to need a supercomputer to process it, the difference will be nothing compared with download speed, etc.
Really, so long as you know that two if statements wont both be true at the same time (and cause an error) then go with whatever you want, whether that's shorter code or something easier to read or whatever.
James
1) faster execution. the code runs faster because after a test has been found to be true, none of the following test cases will be evaluated. since javascript is interpreted, the code may still have to be parsed.
2) more robust code. it's less likely that you will have a bug where the code protected by two different if-statements will be executed.
If your program is including a series of "else if" statements, you might also want to consider using the javascript switch statement.
In the hoary old days of yore, each processor cycle was precious. While hardware improvements may have diminished the importance of a single cycle, it is still a resource the worth of which can only be gained when it isn't wasted.
BUT: The most time consuming activity when executing JavaScript is actually parsing and interpreting it. Whether you use "if if" or "if else if" does not affect parsing because the whole construct has to be parsed. In fact, "if else if" takes a teeny weeny bit longer to parse because it's more text.
In reality you won't usually notice a difference but for reasons already mentioned in this thread it's considered good style to use "else if" when the conditions are disjunctive (only one can be true at a time) or partially disjuntive (only one of a subset of the conditions can be true at a time).
Oh, and by using "else if" you also indicate the disjunctiveness of your conditions to a person reading your code, helping them understand it. Very important.