Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Learning jQuery…Have a few questions Re: Learning jQuery…Have a few questions

#141721
srikarg
Participant

@Rugg

Be careful there. For question #3, the first version will only execute one piece of code since the if, else if, and else are connected. However, the second version can possibly execute two pieces of code as the second if isn’t an if else. This means that if the first condition evaluates to true, it’s code will be run. Then, if the second condition evaluates to true, it will also run.

> I’ve tested both structures…resulting in the same output.

In your case, both versions are ideal for this situation. However, in the future, it may be better to use version #1 as it will avoid the possible error of executing unwanted code. For example, let’s take a look at a simple grade checker:

**Version #1**

var grade = 70; //We can get this from the user.
var letter = ”; //Letter grade
if (grade > 90)
letter = ‘A’;
if (grade > 80)
letter = ‘B’;
if (grade > 70)
letter = ‘C’;

With this version, notice the use of only if’s. Because of this, if the grade is a 100, the letter will become A, then B, then C. This isn’t what we expected correct?

**Version #2**

var grade = 70; //We can get this from the user.
var letter = ”; //Letter grade
if (grade > 90)
letter = ‘A’;
else if (grade > 80)
letter = ‘B’;
else if (grade > 70)
letter = ‘C’;

This will work correctly because if the grade is 100, it will go into the first if and then break out since the first condition evaluates to true.

Clearly, both versions may work for certain situations, but it is best to go with the first one if possible.