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.

Next: The 'else' Statement

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.