Your browser does not support JavaScript!
Upvotes Anonymous 0 User 0

The 'else if' Statement in JavaScript

We can add another condition to an existing if statement, as follows:
if(username == 'Jim') {
    alert('Welcome Jim');
} else if(username = 'Tom') {
    alert('Sorry Tom, you do not have access.');
}
If the username is Tom, then the Sorry Tom... message will be displayed.

Question: So what's the difference between the above, and two separate if statements, as shown below?
if(username == 'Jim') {
    alert('Welcome Jim');
}

if(username = 'Tom') {
    alert('Sorry Tom, you do not have access.');
}
The computer will possibly do more work with the two separate if statements. When the computer runs the separate if statements, it will perform two comparisons ("Is the username Jim?", and "Is the username "Tom?"), even if the username is Jim.
Was this helpful?

Comments

Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License