JavaScript Control, Loops, Arrays

Dr. Greg Bernstein

January 31st, 2021

Control, Loops, and Arrays

Learning Objectives

  • Learn and try out JS control structures
  • Learn to use some of the many loop types in JavaScript
  • Learn about JS Arrays and their methods

Readings

  1. Control flow and error handling

  2. Loops and iteration

  3. Indexed collections.

Control Flow

Blocks

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

{
  statement_1;
  statement_2;
  statement_n;
}

Wakeup 1

Let’s learn about variable scoping with raw blocks.

If Statement

Just like C++ and Java:

if (condition) {
  statement_1;
} else {
  statement_2;
}

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:
    statements_1
    [break;]
  case label_2:
    statements_2
    [break;]
    ...
  default:
    statements_def
    [break;]
}

Exceptions

JavaScript supports exceptions similar to C++, Java, and Python.

  • 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!"; } };

Try/Catch

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.
}

Loops

For Statement

General form

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

Example:

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

Do While Statement

General form:

do
  statement
while (condition);

Example:

var i = 3;
do {
    console.log(i++);
} while(i < 5);

while Statement

General form

while(condition)
    statement

Example:

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

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) {
  statements
}

for in statement

Example:

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) {
  statement
}

Example:

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

Arrays

Creating Arrays

From MDN

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

Array Methods I

Visit MDN Array frequently and often.

DO NOT REINVENT THE WHEEL!!!

Array Methods II

There are array methods to help you perform a huge range of tasks!

  • Searching: find(), findIndex(), includes(), indexOf(), lastIndexOf(searchElement[, fromIndex])

  • Combining and string conversion: concat(), join(deliminator = ',')

  • Stack, List operations: push(), pop(), shift(), unshift()

Array Methods III

  • Modification: slice(start_index, upto_index), splice(index, count_to_remove, addElement1, addElement2, ...), reverse()

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

Functional Array Methods

  • forEach(callback[, thisObject]), map(callback[, thisObject]), filter(callback[, thisObject])

  • every(callback[, thisObject]), some(callback[, thisObject])

  • reduce(callback[, initialValue]), reduceRight(callback[, initialValue])

Wakeup 2

Check your understanding

  • For loop practice!
  • Array loop practice!
// reveal.js plugins