Vainolo's Blog

Archive for the ‘tutorial’ tag

JavaScript Tutorial – Part 5: Statements

leave a comment

While theoretically we can do anything with functions and simple data structures, but for some strange reasons programmers (unlike mathematicians) like their code to be readable and understandable by other human beings. So programming languages (and of course, JavaScript) have some build in statements to help us create more readable and easier to understand programs.

We have the usual suspects: if, for, while, switch, and a new one that I’ll save for the end. Let’s have an example of their use, starting with loop statements:

var min = 0, max = 5;

a = min;
while (a < max) {
    console.info(a);
    a++;
}

a = min;
do {
    console.info(a);
    a++;
} while (a < max);

for (var a = min; a < max; a++) {
    console.info(a);
}

The first loop statement is a while loop, whose formal syntax is:

while (condition) 
    statement

A while is a simple form of loop where the condition is checked and then the statement is executed, repeating this until the condition is false. Pretty simple.

The second loop statement is a do...while loop that is the same as the while loop but the statement of the loop is executed at least once and then the condition is checked.

The last loop statement is a for loop, whose formal syntax is:

for (initialization; condition; update)
    statement

The execution starts by performing all the code in the initialization, then the condition is checked and if it is true, the statement is executed. When it finishes, the update is executed. The condition is checked again and the loop continues always executing update at the end) until condition is false. Note that you can execute many statements in initialization and update using a , (comma) operator between them, like this:

for (var a = 2, b = 4; a < b; a += 2, b += 1) {
    console.info("a=" + a + ", b=" + b);
}

Now let’s see our conditional statements: if and switch:

var a = 1;
if(a === 2) {
    console.info("WAT?");
} else {
    console.info("Yea, that's what I expected");
}

switch (a) {
    case 1:
        console.info("Correct");
        break;
    case 2:
        console.info("WAT?");
        break;
    default:
        console.info("Defaults are always good");
}

Let’s first take a look at the if statements, which is formally defined as:

if (condition1)
    statement1
[else
    statement2]

As the name says, if condition1 is true, statement1 is executed. We can optionally add statement2 that is executed if the condition is false. To check more than one condition, we can chain the condition like this:

if (condition1)
    statement1
else if (condition2)
    statement2
[else
    statement3]

The switch statement is a bit more complex, but sometimes creates more readable code when and there are limited possible values to a variable and limited things we want to do depending on these values. The formal syntax is:

switch (expression) {
    case value1:
        [statement(s)1]
        [break;]
    case value2:
        [statement(s)2]
        [break;]
....
    [default:
        [statement(s)n]]
}

This is a bit more complex, so we’ll take it step by step. First we have an expression that is evaluated and has a value (we’ll call it VALUE). Execution starts top to bottom to find the first case value that is equal to VALUE and if one is found, the code below it is executed. If none is found, and there is a default case, the statements below this case are executed. The location of the default statement doesn’t matter, so you can theoretically put it first, but this is not really what you usually want to do.

One typical error when writing switch statements is to forget the break after the statements of each case, because unlike an if, when a case is matched, ALL of the code below this statement is executed! Not just the code until the next case statement, but ALL of the code below it, until the switch ends, or a break is found. This is good if you want to do the same thing for different case values, like this:

switch (food) {
    case "apple":
    case "orange":
    case "banana":
        console.info("My Favorite");
    case "melon":
        console.info("I Love it!");
        break;
    case "pineapple":
        console.info("I adore these!");
        break;
    default:
        console.info("Not sure, but I'll try");
}

But usually lack of a break is not what you really want.

Going back to loops, their execution can be altered using break and continue. The break statement stops the execution of the loop and continues execution from the first statement after it. The continue statement stops the current iteration of the loop and jumps to check condition in a while loop or to execute update in a for loop:

for (var a = 0; a < 10; <span class="hiddenGrammarError" pre="">a++) {
    if</span> (a == 2)
        continue; // number 2 will not be printed
    if (a > 5)
        break; // loop will end at 6, printing until 5
    console.info(a);
}

// poor man's for loop
var a = 0;
while (true) {
    if (a > 5)
        break;
    console.info(a);
    a++;
}

Last but not least, JavaScript adds a new expression that can be used to iterate over all the attributes of an object. This is a very simple type of reflection that is useful many times. Formally, when attr is a variable name and object is a variable that contains an object reference, the statements is as follows:

 
for (var attr in object) 
  statement

And now a simple example of how this works, a short way to print all attributes of an object and their values:

var obj = { a: 1, b: 2 };
for (var attr in obj) {
    console.info(attr+"="+obj[attr]);
}

I thought I would get to talk also about operators here, and about what equal means in JavaScript (same object? same values?) but this tutorial is getting long so I’ll leave it for next time. Happy JavaScripting!

Written by vainolo

May 17th, 2015 at 10:05 pm

%d bloggers like this: