PewPew!

by James Park

and Front-end Development by Woo Cheol Hyun (not even though)



Part 2: Logic Expressions

You now (hopefully) hold a decent command of fundamental Javascript. Maybe my site is bad and you actually don't. But moving on...

For loops are very useful and all, but they have limitations too. You can use them to sum together many numbers, such as all numbers from 1 to 100, but what if you want to sum together all numbers from 1 to 100 except multiples of 5? You could use several for loops to skip the multiples, but that would be rather inefficient.

What would you use to skip multiples of 5? The answer: if statements.

if statements

Consider the following code:

var sum = 0;
for (var i = 1; i <= 100; i++)
{
  if (i % 5 != 0)
    {
      sum += i;
    }
}
alert(sum);

Random Fact! <= is less than or equal to. >= is greater than or equal to.

This code will, indeed, not add any multiples of 5. How? Let's separate the if statement from the rest of the code.

if (i % 5 != 0)
{
    sum += i;
} 

Something within the curly braces of an if statement will only be read if the truth expression in the parentheses evaluates to true.

if (something is true)
{
    //code... 
}

When does i % 5 != 0 evaluate to true? Hint: != (is not equal to) is the opposite of == (equal to). answer