Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

484 LESSON 17: Introducing JavaScript


You can also use the! operator, which reads as “not,” to negate any Boolean expression.
For example, if you enter !true in the Console, the result of the expression will be false.
If you want to negate an expression that uses a conditional operator, you’ll need to use
parentheses. For example, try this expression in the Console:
!(1 == 2)
The result will be true.

Loops
You’ll occasionally want a group of statements to be executed more than once. JavaScript
supports two kinds of loops. The first, the for loop, is ideal for situations in which you
want to execute a group of statements a specific number of times. The second, the while
loop, is useful when you want a set of statements to be executed until a condition is satis-
fied.
for Loops Here’s a for loop:
for (var count = 1; count <= 10; count++) {
console.log("Iteration number " + count);
}

The loop starts with the for keyword, followed by all the information needed to specify
how many times the loop body will be executed. (Trips through a loop are referred to as
iterations .) Three expressions are used to define a for loop. First, a variable is declared
to keep track of the loop iterations. The second is a Boolean expression (evaluates to true
or false) that terminates the loop when it is false. The third is an expression that incre-
ments the loop counter so that the loop condition will eventually be satisfied. In the pre-
ceding example, I declared the variable count with an initial value of 1. I specified that
the loop will execute until the value of count is no longer less than or equal to 10. Then I
used an operator you haven’t seen, ++, to increment the value of count by one each time
through the loop.
The body of the loop uses console.log to print out a message in the console every time
the loop executes. The console object refers to the Console in the web developer tools,
and the log method prints whatever is passed as an argument to the console directly. It’s
useful for debugging, especially when you add it to your scripts within pages to get a
sense of the state of your scripts while they’re running.

As you can see, the for statement is self-contained. The count
variable is declared, tested, and incremented within that state-
ment. You shouldn’t modify the value of count within the body of
your loop unless you’re absolutely sure of what you’re doing.

CAUTION
Free download pdf