JavaScript Tutorial – Part 5: Statements

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) {;

a = min;
do {;
} while (a < max);

for (var a = min; a < max; a++) {;

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

while (condition) 

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)

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) {"a=" + a + ", b=" + b);

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

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

switch (a) {
    case 1:"Correct");
    case 2:"WAT?");
    default:"Defaults are always good");

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

if (condition1)

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)
else if (condition2)

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:
    case value2:

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":"My Favorite");
    case "melon":"I Love it!");
    case "pineapple":"I adore these!");
    default:"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;

// poor man's for loop
var a = 0;
while (true) {
    if (a > 5)

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) 

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) {"="+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!

Reference: JavaScript Tutorial – Part 5: Statements from our WCG partner Arieh Bibliowicz at the Vainolo’s Blog blog.

Arieh Bibliowicz

Arieh is a longtime programmer with more than 10 years of experience in enterprise grade software projects. He has worked as server-size programmer, team leader and system architect in a mission-critical high-availability systems. Arieh is currently a Program Manager (PM) in the Microsoft ILDC R&D center for the Azure Active Directory Application Proxy, and also a PhD student at the Technion where he is developing a Visual Programming Language based on the graphical language of the Object-Process Methodology, using Java and the Eclipse platform.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button