Arrays and Control Structures in Object-Oriented JavaScript

Exclusive offer: get 50% off this eBook here
Object-Oriented JavaScript

Object-Oriented JavaScript — Save 50%

Create scalable, reusable high-quality JavaScript applications and libraries

$23.99    $12.00
by Stoyan Stefanov | May 2009 | AJAX Web Development

In this article by Stoyan Stefanov, you will learn about the basics of Object-Oriented JavaScript which will cover the following:

  • Arrays
  • Flow control statements, such as loops and if-else conditions

Arrays

Now that you know the basic primitive data types in JavaScript, it's time to move to a more interesting data structure—the array.

To declare a variable that contains an empty array, you use square brackets with nothing between them:

>>> var a = [];
>>> typeof a;
"object"

typeof returns "object", but don't worry about this for the time being, we'll get to that when we take a closer look at objects.

To define an array that has three elements, you do this:

>>> var a = [1,2,3];

When you simply type the name of the array in the Firebug console, it prints the contents of the array:

>>> a
[1, 2, 3]

So what is an array exactly? It's simply a list of values. Instead of using one variable to store one value, you can use one array variable to store any number of values as elements of the array. Now the question is how to access each of these stored values?

The elements contained in an array are indexed with consecutive numbers starting from zero. The first element has index (or position) 0, the second has index 1 and so on. Here's the three-element array from the previous example:

Index

Value

0

1

1

2

2

3

In order to access an array element, you specify the index of that element inside square brackets. So a[0] gives you the first element of the array a, a[1] gives you the second, and so on.

>>> a[0]
1
>>> a[1]
2

Adding/Updating Array Elements

Using the index, you can also update elements of the array. The next example updates the third element (index 2) and prints the contents of the new array.

>>> a[2] = 'three';
"three"
>>> a
[1, 2, "three"]

You can add more elements, by addressing an index that didn't exist before.

>>> a[3] = 'four';
"four"
>>> a
[1, 2, "three", "four"]

If you add a new element, but leave a gap in the array, those elements in between are all assigned the undefined value. Check out this example:

>>> var a = [1,2,3];
>>> a[6] = 'new';
"new"
>>> a
[1, 2, 3, undefined, undefined, undefined, "new"]

Deleting Elements

In order to delete an element, you can use the delete operator. It doesn't actually remove the element, but sets its value to undefined. After the deletion, the length of the array does not change.

>>> var a = [1, 2, 3];
>>> delete a[1];
true
>>> a
[1, undefined, 3]

Arrays of arrays

An array can contain any type of values, including other arrays.

>>> var a = [1, "two", false, null, undefined];
>>> a
[1, "two", false, null, undefined]
>>> a[5] = [1,2,3]
[1, 2, 3]
>>> a
[1, "two", false, null, undefined, [1, 2, 3]]

Let's see an example where you have an array of two elements, each of them being an array.

>>> var a = [[1,2,3],[4,5,6]];
>>> a
[[1, 2, 3], [4, 5, 6]]

The first element of the array is a[0] and it is an array itself.

>>> a[0]
[1, 2, 3]

To access an element in the nested array, you refer to the element index in another set of square brackets.

>>> a[0][0]
1
>>> a[1][2]
6

Note also that you can use the array notation to access individual characters inside a string.

>>> var s = 'one';
>>> s[0]
"o"
>>> s[1]
"n"
>>> s[2]
"e"

There are more ways to have fun with arrays, but let's stop here for now, remembering that:

  • An array is a data store
  • An array contains indexed elements
  • Indexes start from zero and increment by one for each element in the array
  • To access array elements we use the index in square brackets
  • An array can contain any type of data, including other arrays
Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Conditions and Loops

Conditions provide a simple but powerful way to control the flow of execution through a piece of code. Loops allow you to perform repeating operations with less code. Let's take a look at:

  • if conditions,
  • switch statements,
  • while, do-while, for, and for-in loops.

Code Blocks

Let's start by clarifying what a block of code is, as blocks are used extensively when constructing conditions and loops.

A block of code consists of zero or more expressions enclosed in curly brackets.

{
var a = 1;
var b = 3;
}

You can nest blocks within each other indefinitely:

{
var a = 1;
var b = 3;
var c, d;
{
c = a + b;
{
d = a - b;
}
}
}

Best Practice Tips

  • Use end-of-line semicolons. Although the semicolon is optional when you have one expression per line, it's good to develop the habit of using them. For best readability, the individual expressions inside a block should be placed one per line and separated by semi-colons.
  • Indent any code placed within curly brackets. Some people use one tab indentation, some use four spaces, and some use two spaces. It really doesn't matter, as long as you're consistent. In the example above the outer block is indented with two spaces, the code in the first nested block is indented with four spaces and the innermost block is indented with six spaces.
  • Use curly brackets. When a block consists of only one expression, the curly brackets are optional, but for readability and maintainability, you should get into the habit of always using them, even when they're optional.

Ready to jump into loops and ifs? Note that the examples in the following sections require you to switch to the multi-line Firebug console.

if Conditions

Here's a simple example of an if condition:

var result = '';
if (a > 2) {
result = 'a is greater than 2';
}

The parts of the if condition are:

  • The if statement
  • A condition in parentheses—"is a greater than 2?"
  • Code block to be executed if the condition is satisfied

The condition (the part in parentheses) always returns a boolean value and may contain:

  • A logical operation: !, && or ||
  • A comparison, such as ===, !=, >, and so on
  • Any value or variable that can be converted to a boolean
  • A combination of the above

There can also be an optional else part of the if condition. The else statement is followed by a block of code to be executed if the condition was evaluated to false.

if (a > 2) {
result = 'a is greater than 2';
} else {
result = 'a is NOT greater than 2';
}

In between the if and the else, there can also be an unlimited number of else if conditions. Here's an example:

if (a > 2 || a < -2) {
result = 'a is not between -2 and 2';
} else if (a === 0 && b === 0) {
result = 'both a and b are zeros';
} else if (a === b) {
result = 'a and b are equal';
} else {
result = 'I give up';
}

You can also nest conditions by putting new conditions within any of the blocks.

if (a === 1) {
if (b === 2) {
result = 'a is 1 and b is 2';
} else {
result = 'a is 1 but b is not 2';
}
} else {
result = 'a is not 1, no idea about b';
}

Checking if a Variable Exists

It's often useful to check whether a variable exists. The laziest way to do this is simply putting the variable in the condition part of the if, for example if (somevar) {...}, but this is not necessarily the best method. Let's take a look at an example that tests whether a variable called somevar exists, and if so, sets the result variable to yes:

>>> var result = '';
>>> if (somevar){result = 'yes';}
somevar is not defined
>>> result;
""

This code obviously works, because at the end result was not "yes". But firstly, the code generated a warning: somevar is not defined and as a JavaScript whiz you don't want your code to do anything like that. Secondly, just because if (somevar) returned false doesn't mean that somevar is not defined. It could be that somevar is defined and initialized but contains a falsy value, like false or 0.

A better way to check if a variable is defined is to use typeof.

>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""

typeof will always return a string and you can compare this string with "undefined". Note that the variable somevar may have been declared but not assigned a value yet and you'll still get the same result. So when testing with typeof like this, you're really testing whether the variable has any value (other than the value undefined).

>>> var somevar;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""
>>> somevar = undefined;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
""

If a variable is defined and initialized with any value other than undefined, its type returned by typeof is no longer "undefined".

>>> somevar = 123;
>>> if (typeof somevar !== "undefined"){result = 'yes';}
>>> result;
"yes"

Alternative if Syntax

When you have a very simple condition you can consider using an alternative if syntax. Take a look at this:

var a = 1;
var result = '';
if (a === 1) {
result = "a is one";
} else {
result = "a is not one";
}

The if condition can be expressed simply as:

var result = (a === 1) ? "a is one" : "a is not one";

You should only use this syntax for very simple conditions. Be careful not to abuse it, as it can easily make your code unreadable.

The ? is called ternary operator.

Switch

If you find yourself using an if condition and having too many else if parts, you could consider changing the if to a switch.

var a = '1';
var result = '';
switch (a) {
case 1:
result = 'Number 1';
break;
case '1':
result = 'String 1';
break;
default:
result = 'I don't know';
break;
}
result;

The result of executing this will be "String 1". Let's see what the parts of a switch are:

  • The switch statement.
  • Some expression in parentheses. The expression most often contains a variable, but can be anything that returns a value.
  • A number of case blocks enclosed in curly brackets.
  • Each case statement is followed by an expression. The result of the expression is compared to the expression placed after the switch statement. If the result of the comparison is true, the code that follows the colon after the case is executed.
  • There is an optional break statement to signal the end of the case block. If this break statement is reached, we're all done with the switch. Otherwise, if the break is missing, we enter the next case block, which should be avoided.
  • There's an optional default statement, which is followed by a block of code that is executed if none of the previous cases evaluated to true.

In other words, the step-by-step procedure for executing a switch statement is as follows:

  1. Evaluate the switch expression found in parentheses, remember it.
  2. Move to the first case, compare its value with the one from step 1.
  3. If the comparison in step 2 returns true, execute the code in the case block.
  4. After the case block is executed, if there's a break statement at the end of it, exit the switch.
  5. If there's no break or step 2 returned false, move on to the next case block. Repeat steps 2 to 5.
  6. If we're still here (we didn't exit in step 4), execute the code following the default statement.

Best Practice Tips

  • Indent the case line, and then further indent the code that follows it.
  • Don't forget to break. Sometimes you may want to omit the break intentionally, but that's rare. It's called a fall-through and should always be documented because it may look like an accidental omission. On the other hand, sometimes you may want to omit the whole code block following a case and have two cases sharing the same code. This is fine, but doesn't change the rule that if there's code that follows a case statement, this code should end with a break. In terms of indentation, aligning the break with the case or with the code inside the case is a personal preference; again, being consistent is what matters.
  • Use the default case. This will help you make sure you have a meaningful result after the switch, even if none of the cases matched the value being switched.

Loops

if-else and switch statements allow your code to take different paths, as if you're at a crossroads and decide which way to go depending on a condition. Loops, on the other hand, allow your code to take a few roundabouts before merging back into the main road. How many repetitions? That depends on the result of evaluating a condition before (or after) each iteration.

Let's say you are (your program execution is) traveling from A to B. At some point, you reach a place where you evaluate a condition C. The result of evaluating C tells you if you should go into a loop L. You make one iteration. Then you evaluate the condition once again to see if another iteration is needed. Eventually, you move on your way to B.

An infinite loop is when the condition is always true and your code gets stuck in the loop "forever". This is, of course, is a logical error and you should look out for such scenarios.

In JavaScript, there are four types of loops:

  • while loops
  • do-while loops
  • for loops
  • for-in loops

While Loops

Object-Oriented JavaScript

while loops are the simplest type of loop. They look like this:

var i = 0;
while (i < 10) {
i++;
}

The while statement is followed by a condition in parentheses and a code block in curly brackets. As long as the condition evaluates to true, the code block is executed over and over again.

Do-while loops

do-while loops are a slight variation of the while loops. An example:

var i = 0;
do {
i++;
} while (i < 10)

Here, the do statement is followed by a code block and a condition after the block. This means that the code block will always be executed, at least once, before the condition is evaluated.

If you initialize i to 11 instead of 0 in the last two examples, the code block in the first example (the while loop) will not be executed and i will still be 11 at the end, while in the second (do-while loop), the code block will be executed once and i will become 12.

For Loops

for is the most widely used type of loop and you should make sure you're comfortable with this one. It requires a just little bit more in terms of syntax.

Object-Oriented JavaScript

In addition to the condition C and the code block L, you have the following:

  • Initialization—some code that is executed before you even enter the loop (marked with 0 in the diagram)
  • Increment—some code that is executed after every iteration (marked with ++ in the diagram)

The most widely used pattern of using a for loop is:

  • In the initialization part you define a variable, most often called i, like this: var i = 0;
  • In the condition part you compare i to a boundary value, like i < 100
  • In the increment part, you increase i by 1, like i++

Here's an example:

var punishment = '';
for (var i = 0; i < 100; i++) {
punishment += 'I will never do this again, ';
}

All three parts (initialization, condition, increment) can contain multiple expressions separated by commas. You can rewrite the example and define the variable punishment inside the initialization part of the loop.

for (var i = 0, punishment = ''; i < 100; i++) {
punishment += 'I will never do this again, ';
}

Can you move the body of the loop inside the increment part? Yes, you can, especially as it's a one-liner. This will give you a loop that looks a little awkward, as it has no body:

for (var i = 0, punishment = '';
i < 100;
i++, punishment += 'I will never do this again, ')
{
// nothing here
}

These three parts are actually all optional. Here's another way of rewriting the same example:

var i = 0, punishment = '';
for (;;) {
punishment += 'I will never do this again, ';
if (++i == 100) {
break;
}
}

Although the last rewrite works exactly the same way as the original, it is longer and harder to read. It's also possible to achieve the same result by using a while loop. But for loops make the code tighter and more robust, because the mere syntax of the for loop makes you think about the three parts (initialization, condition, increment) and thus, helps you reconfirm your logic and avoid situations such as being stuck in an infinite loop.

for loops can be nested within each other. Here's an example of a loop that is nested inside another loop and assembles a string containing 10 rows and 10 columns of asterisks. Think of i being the row and j being the column of an "image".

var res = 'n';
for(var i = 0; i < 10; i++) {
for(var j = 0; j < 10; j++) {
res += '* ';
}
res+= 'n';
}

The result is a string like:

"
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
"

Here's another example that uses nested loops and a modulus operation in order to draw a little snowflake-like result.

var res = 'n', i, j;
for(i = 1; i <= 7; i++) {
for(j = 1; j <= 15; j++) {
res += (i * j) % 8 ? ' ' : '*';
}
res+= 'n';
}
"
*
* * *
*
* * * * * * *
*
* * *
*
"

For-in Loops

The for-in loop is used to iterate over the elements of an array (or an object, as we'll see later). This is its only use; it cannot be used as a general-purpose repetition mechanism that replaces for or while. Let's see an example of using a for-in to loop through the elements of an array. But bear in mind that this is for informational purposes only, as for-in is mostly suitable for objects, and the regular for loop should be used for arrays.

In this example, we'll iterate over all of the elements of an array and print out the index (the key) and the value of each element:

var a = ['a', 'b', 'c', 'x', 'y', 'z'];
var result = 'n';
for (var i in a) {
result += 'index: ' + i + ', value: ' + a[i] + 'n';
}
The result is:
"
index: 0, value: a
index: 1, value: b
index: 2, value: c
index: 3, value: x
index: 4, value: y
index: 5, value: z
"

Comments

One last thing for this article: comments. Inside your JavaScript code you can put comments. These are ignored by the JavaScript engine and don't have any effect on how the program works. But they can be invaluable when you revisit your code after a few months, or transfer the code to someone else for maintenance.

Two types of comments are allowed:

  • Single line comments—start with // and end at the end of the line
  • Multi-line comments—start with /* and end with */ on the same line or any subsequent line. Note that any code in between the comment start and the comment end will be ignored.

Some examples:

// beginning of line
var a = 1; // anywhere on the line
/* multi-line comment on a single line */
/*
comment
that spans
several lines
*/

There are even utilities, such as JSDoc, that can parse your code and extract meaningful documentation based on your comments.

Summary

In this article, you learned a lot about the basic building blocks of a JavaScript program. You learned how to use arrays to store and access data, and also saw different ways to control the flow of your program—using conditions (if-else or switch) and loops (while, do-while, for, for-in).

Object-Oriented JavaScript Create scalable, reusable high-quality JavaScript applications and libraries
Published: July 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Stoyan Stefanov

Stoyan Stefanov is a Facebook engineer, author, and speaker. He talks regularly about web development topics at conferences and his blog www.phpied.com, and also runs a number of other sites, including JSPatterns.com—a site dedicated to exploring JavaScript patterns. Previously at Yahoo!, Stoyan was the architect of YSlow 2.0 and creator of the image optimization tool Smush.it.

A "citizen of the world", Stoyan was born and raised in Bulgaria, but is also a Canadian citizen, currently residing in Los Angeles, California. In his offline moments, he enjoys playing the guitar, taking flying lessons, and spending time at the Santa Monica beaches with his family.

Books From Packt


PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Learning jQuery 1.3
Learning jQuery 1.3

JBoss Tools 3 Developers Guide
JBoss Tools 3 Developers Guide

WordPress Plugin Development: Beginner's Guide
WordPress Plugin Development: Beginner's Guide

Apache MyFaces Trinidad 1.2: A Practical Guide
Apache MyFaces Trinidad 1.2: A Practical Guide

Grails 1.1 Web Application Development
Grails 1.1 Web Application Development

Seam 2.x Web Development
Seam 2.x Web Development


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
t
f
v
G
x
k
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software