Code blocks

A block of code is a group of statements that are you want to be treated as a unit. They're still executed sequentially (one after another), but they go together in the larger structure of the program.

A block of code in Javascript is surrounded by braces - { }.

    {
    x = 1;
    y = x + 1;
    }

The first use of this is for the "body" of an if-statement - to have multiple statements that are run if the test is true. (It can also be used in the else part, of course.)

if (x == 1)
    {
    y = x + 1;
    z = y * 3;
    }
else
    {
    y = x - 1;
    z = y * 7;
    }





Loops

Looping (or "iteration") is when you want the computer to run a statement, or set of statements, multiple times.

The basic form of this is a while-loop, similar to an if-statement, except the code is run as long as the test is true, instead of just once if it's true.

Compare:

count = 5;
if (count > 0)
    {
    alert(count);
    count = count - 1;
    }
alert('Afterwards: ' + count);
count = 5;
while (count > 0)
    {
    alert(count);
    count = count - 1;
    }
alert('Afterwards: ' + count);


Creative Commons License
This document is by Dave Pape, and is released under a Creative Commons License.