JavaScript: Control, Loops, Arrays

Dr. Greg Bernstein

Updated August 29th, 2019

Control, Loops, and Arrays


  1. Control flow and error handling

  2. Loops and iteration

  3. Indexed collections.

Control Flow


Just like C++ and Java. Used to group statements:


If Statement

Just like C++ and Java:

if (condition) {
} else {

Falsey Values

You’ll sometimes see very terse JavaScript conditional statements. These take advantage of the following evaluating to false in an if:

false, undefined, null, 0, NaN, and the empty string ("")

Switch Statement

Similar to C++ and Java, however the labels are usually strings. Don’t forget the break statement!

switch (expression) {
  case label_1:
  case label_2:


JavaScript supports exceptions similar to C++ and Java.

  • There is a throw statement you can use to throw any object including numbers and strings
  • There are standard Error objects you can throw.
  • You use a try/catch block when you want to handle exceptions.

Throw Statement

Examples from MDN:

throw 'Error2';   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };


Basic structure:

try {
    // A bunch of statements
    // that could throw an exception
catch(e) {
    // Statements to handle the exception
    // The exception is gotten via the "e"
    // parameter. You can give this parameter any name.


For Statement

General form

for ([initialExpression]; [condition]; [incrementExpression])


for(var i = 0; i < 10; i++) {
    console.log(i.toString() + "vcubed = " + i*i*i);

Do While Statement

General form:

while (condition);


var i = 3;
do {
} while(i < 5);

while Statement

General form



message = "Code! ";
while (message.length < 40) {
    message += "The Web, ";

break Statement

From MDN

Use the break statement to terminate a loop or switch statement.

continue Statement

From MDN

The continue statement can be used to restart a while, do-while or for statement. It terminates the current iteration of the innermost enclosing while, do-while, or for statement and continues execution of the loop with the next iteration. In a while loop, it jumps back to the condition. In a for loop, it jumps to the increment-expression.

for in statement

For enumerating properties of objects:

for (variable in object) {

for in statement


myObject = {name: "Dr. B", topic: "Web Dev", fun: true};
for (var prop in myObject) {
    console.log("Property: " + prop + ", has value: " + myObject[prop]);

Caution objects other than those you directly create may inherit many other properties. Use the method .hasOwnProperty(propString) to test.

for of Statement

A nicer way to loop over iterable objects such as arrays.

for (variable of object) {


myArray = ["Let's", "program", "the", "web"];
for (var word of myArray) {


Creating Arrays

From MDN

var arr = new Array(element0, element1, ..., elementN);
var arr = Array(element0, element1, ..., elementN);
var arr = [element0, element1, ..., elementN];

Creating an Array with Empty Slots

From MDN. I’ve never had occasion to do this.

// arrayLength must be an integer
var arr = new Array(arrayLength);
var arr = Array(arrayLength);

Populating an Array

From MDN.

var emp = [];
emp[0] = 'Casey Jones';
emp[1] = 'Phil Lesh';
emp[2] = 'August West';

Array Methods

  • concat(): joins two arrays and returns a new array.

  • join(deliminator = ','): joins all elements of an array into a string.

  • push(): adds one or more elements to the end of an array and returns the resulting length of the array.

Array Methods

  • pop(): removes the last element from an array and returns that element.

  • shift(): removes the first element from an array and returns that element.

  • unshift(): adds one or more elements to the front of an array and returns the new length of the array.

Array Methods

  • slice(start_index, upto_index): extracts a section of an array and returns a new array.

  • splice(index, count_to_remove, addElement1, addElement2, ...): removes elements from an array and (optionally) replaces them. It returns the items which were removed from the array.

  • reverse(): transposes the elements of an array: the first array element becomes the last and the last becomes the first.

Array Methods

  • sort(): sorts the elements of an array. Can take a callback function for custom sorting.

  • indexOf(searchElement[, fromIndex]): searches the array for searchElement and returns the index of the first match.

  • lastIndexOf(searchElement[, fromIndex]): works like indexOf, but starts at the end and searches backwards.

Array Methods

  • forEach(callback[, thisObject]): executes callback on every array item.

  • map(callback[, thisObject]): returns a new array of the return value from executing callback on every array item.

  • filter(callback[, thisObject]): returns a new array containing the items for which callback returned true.

Array Methods

  • every(callback[, thisObject]): returns true if callback returns true for every item in the array.

  • some(callback[, thisObject]): returns true if callback returns true for at least one item in the array.

  • reduce(callback[, initialValue]): applies callback(firstValue, secondValue) to reduce the list of items down to a single value.

Array Methods

  • reduceRight(callback[, initialValue]): works like reduce(), but starts with the last element.