Breadcrumbs

Too Easy JavaScript - Arrays and Switch [4]

After the basics of any programming language there is always the next step forward. With if...else statements you move on to learn switch statements. From learning variables you move on to working with arrays. In Part 4 of Too Easy JavaScript we'll learn the basics of complex conditional statements and working with arrays.

If you desire to review conditional statements and variables then read Parts 2 and 3 of Too Easy JavaScript.

Nested if...else Statements

Nested if...else statements are used if you need more than one "if". Although they're messy and a bad practice, programmers will always find themselves in situations where multiple conditions are required, later in this lesson we will learn JavaScript's replacement for nested if...else statements. Nested conditional statements can become huge, confusing code blocks.

Code: JavaScript

var number = 3;
if (number == 1) {
    alert("The number equals 1.");
}
else {
    if (number == 2) {
        alert("The number equals 2.");
    }
    else {
        if (number == 3) {
            alert("The number equals 3.");
        }
        else {
            alert("The number doesn't match anything.");
        }
    }
}

There are many problems with nested if...else statements - they're hard to read, they take the browser longer to interpret, and they're not necessary. JavaScript provides us with a method to replace nested if...else statements - switch statements.

Switch Statements

JavaScript offers developers the switch statement to replace nested if...else statements. The format for a switch statement is as follows:

Code: JavaScript

switch (expression) {
    case label1:
        // Code to be executed
    break;
    case label2:
        // Code to be executed
    break;
    default:
        // Default code to be executed
    break;
}

Switch statements work by first evaluating the given expression and then matching the resulting value to a user specified label. Each label has associated code that will execute when its label is matched.

Each switch statement uses the case keyword to denote a label and the break keyword to end it. A label's associated code is contained within the label and break keyword. Switch statements can also use the default keyword to specify code that is executed if the expression's result doesn't match any of the labels.

Code: JavaScript

var number = 3;
switch (number) {
    case 1:
        alert("The number equals 1.");
    break;
    case 2:
        alert("The number equals 2.");
    break;
    case 3:
        alert("The number equals 3.");
    break;
    default:
        alert("The number doesn't match anything.");
    break;
}

Using a switch statement we were able to transform messy, nested if...else statements into a comprehendible switch statement. A label may be a number, string, or boolean. Switch statements are an effective way for matching an expression to multiple conditions.

Basics of Arrays

Organization is a key for good programming. Arrays function similar to variables, except they allow you to store multiple values. The advantage of arrays is the ability to store related values neatly under one name, or address. Arrays serve as a replacement for a list of individual variables.

Code: JavaScript

var employee1 = "Ethan";
var employee2 = "Matt";
var employee3 = "Daniel";
var employee4 = "Kristoffer";
var employee5 = "Markus";

Taking these variables, storing a list of employee names, we can confine the list into a practical container, or array.

Code: JavaScript

var employee = new Array("Ethan","Matt","Daniel","Kristoffer","Markus");

Each value in an array has two parts - the key and the element. A value's key is used to reference to the value, while the element holds the initial value. If you fail to set a key yourself JavaScript will create an incrementing integer to represent each value. Also, take note that an array's key will start on zero rather than one. Therefore, an array with three values has keys for 0, 1, and 2.

array[key] = element;

To create a new array you use the new keyword to create an Array object, which is built into JavaScript.

Code: JavaScript

var employee = new Array();
var employee = new Array(5); // Using optional argument

The array object optionally allows you to pass an argument, to the constructor of the array, that determines how many values it has the ability to hold. Unless you know specifically how many values the array will hold, do not take this optional step. An array's length which is determined by random values or user input may cause a fence post error, where you write past the end of an array. Some browsers can handle this type of dilemma, although it isn't good programming.

To add new elements into the array you can either declare them when the array is initialized, by using a specific array key, or by using an array's length property. Each method is useful depending on the given situation.

Code: JavaScript

// Declare through initialization
var employee = new Array("Ethan","Matt","Daniel","Kristoffer","Markus");

// Declare using keys
var employee = new Array();
employee[0] = "Ethan";
employee[1] = "Matt";
employee[2] = "Daniel";
employee[3] = "Kristoffer";
employee[4] = "Markus";

Both of the above methods, insertion through initialization and keys, will produce identical arrays. Each have situations where they would have the advantage over the other.

An array's length property enables you to do many things with an array, from inserting values to looping through an array's elements. To access the length property place the property operator (.) and "length" following the identifier, or name, of the array.

Code: JavaScript

employee.length;

When inserting data the length property allows you to add values to an array when you don't know what the last incremental key was. Due to the length of an array always being one longer than the last key, you can add a value without placing anything between the brackets.

Code: JavaScript

employee[employee.length] = "Johnny";

Looping Through Array Elements

Once you've created an array and added elements to it you can start working with the array. There is a multitude of functions and processes that go with arrays. A common task is to loop through an entire array.

To loop through an array we use a for loop, the most practical control structure for this situation.

Code: JavaScript

var employee = new Array("Ethan","Matt","Daniel","Kristoffer","Markus");

for(var x = 0; x < employee.length; x++) {
    document.write(employee[x] + "<br />");
}

Summary

In Part 4 of Too Easy Javascript you have learned a replacement for nested if...else statements and the fundamentals of arrays. In Part 5 we will look into some of JavaScript's built in functions and how to make our own functions.