Topic 1: Loops, Conditional Statements, Functions, Variables, Parameters, Arrays, Associative Arrays

Variables

Variables are containers for values. The values can be numbers, strings, arrays function, booleans, etc. To use a variable, first you have to declare it using the keyword var. It is also a good idea to initialize it, or give it a starting value. This can be done in one statement or separately.

var i = "";
var number;
var number = 0;
var valid = false;

The values inside variables can be changed by using the assignment operator (=) or by incrementing (number++). There is no need to use the keyword var again on a variable that has already been declared.

i = "red";
number-2;
valid = true;

Arrays

Arrays allow you to store multiple values in one variable. There are two ways to create an array.

Declare a new variable and then use the assignment operator to add a bracketed comma separated list.

Declare a new variable and then use the new keyword to create a new array with the number of array elements in parenthesis. In this case, the elements in the array will be undefined and need to be initialized or assigned values.

var dogs = ["Fido", "Spot", "Fluffy", "Spike"];
var cats = new array(3);

To access an element in an array, you use the variable name followed by the index of the element in brackets. Remember the first element in an array has an index of 0. You can add or replace certain elements in an array using the assignment operator. You can use a for loop to access all the elements in an array.

dogs[0]; // The value is currently "Fido"
cats[0] = "Felix"; // This would go in the first spot of the cats array;
cats[1] = "Tom";
cats[2] = "Garfield";

Associative Arrays

Associative Arrays are objects. They have similarities and differences to arrays. They are similar in that they allow you to store multiple values in one variable. They are different than arrays in several key ways. First, instead of having indexes, the elements in an associative array have key value pairs. This makes the way you create an associative array, and the way you access elements in it different than arrays.

To create an associative array, you declare the variable then use the assignment operator to add a list of key value pairs inside a curly bracketed list.

Key value pairs have two parts, the key and the value. The value is the information being stored in the array, and the key is a keyword that will be used to access the value. Here is an example.

var john = {firstName: "John", lastName: "Doe", age: "42", sex: "male", marStatus: single};

To access a value, you use the keyword associated with it. You can't use an index. For instance john[3] will return as undefined. Instead you would access a value in one of the two ways shown below.

john.age;
john['age'];

var info = john.firstName + " " + john["lastName"] + " is " + john.age + " years old.";

To access all of the values inside an associative array, you would use a for in loop. Read on to learn more about for in loops.

Loops

Loops are used to repeat a block of code. If the same thing needs to happen in a program more than once, rather than typing the block of code over and over, a loop can be used to cycle through the code a certain number of times, or until a condition is met.

There are 4 kinds of loops:

for loop

for loops repeat until a condition is no longer true. They are useful when you know how many times a loop needs to be repeated. The following for loop will repeat 10 times, and will print a message that contains the numbers 0-9

var message = ""
for (var i = 0; i < 10; i++) {
  message += i + " "
}
document.getElementById("result1").innerHTML = "for loop result=" + message

for in loop

The number of times a for in loop repeats is determined by the number of elements in an object. for in loops are useful when working with arrays or objects. The following for in loop will repeat 5 times because there are 5 elements in the associative array. For in loops can also be used to initialize all the elements of an object or array.

var output = "John-";
var n;
for (n in john) {
  output += n + ": " + john[n];
}
document.getElementById("output").innerHTML = "for in result = " + output;

while loop

A while loop is good whether or not you know how many times the block of code needs to be repeated. It repeats the code until a certain condition is met. Here are some examples:

while(i < 10)

This will repeat the loop until the counter i reaches 10.

while(!valid)

This will repeat as long as the boolean value of the variable valid is false.

var j = 0;
var message = ""
var cat = "";
while(j < cats.length) {
cat = cats[j];
  message += cats + " ";
  j++;
}
document.getElementById("result2").innerHTML = "while loop result = "

do while loop

A do while loop is similar to a while loop, except it repeats once before checking to see if the condition is met. A do while loop should be used if the code needs to be executed at least once whether the condition is met or not. Here is an example of a do while loop. Notice on the example, that the condition is not true. However, the result includes one dog because the loop executed once before checking the condition.

var k = 3;
var message = "";
var dog = "";
do {
var dog = dogs[k];
  message += dog + ", ";
  k++;
} while(i < 3);
document.getElementById("result3").innerHTML = "do while loop result =" + message;

Conditionals

Conditional statements allow for decision making within a program. Certain blocks of code will be executed or skipped depending on certain conditions. There are several different kinds of conditional statements. They include:

if statements

If statements should be used when there is only one condition that is either true or false. If the condition is true, the block of code is executed. If it is false, the block is skipped.

var color = 3;
if (color < 5) {
  document.getElementById(output2).innerHTML = "The sky is blue."
}

if else statements

An if else statement should be used when you have one condition, with two different blocks of code to be executed depending on whether the condition is true or false. If the condition is true, run the first block of code and skip the second, else if it is false, skip the first block and run the second.

var number = 7;
if (number < 5) {
  document.getElementById("condition2").innerHTML = "The number " + number + " is less than 5";
} else {
  document.getElementById("condition2").innerHTML = "The number " + number + " is greater than 5";
}

if else if statements

An if else statement is useful when there are several different conditions, each with different results. The first condition is checked, and if it is true, the first block of code is executed and the rest of the if else statement is skipped. If the first is false, the first block of code is skipped and the second condition is checked. This is repeated until a condition is found to be true, and its block of code is executed. Once a block of code is executed the rest of the if else is skipped. Even if a later condition is true within the if else, it will be skipped. The final part of an if else statement is an else statement, without a condition. The final else block of code is executed if none of the conditions are true.

This code generates a random number and then returns a message based on that number. You can refresh the page to see it work with different numbers.

var randomNumber = Math.floor(Math.random() * (100 - 1) + 1);
if (randomNumber <= 25) {
  document.getElementById("condition3").innerHTML = "The number " + randomNumber + " is between 1 and 25";
} else if (randomNumber <= 50) {
  document.getElementById("condition3").innerHTML = "The number " + randomNumber + " is between 25 and 50";
} else if (randomNumber <= 75) {
  document.getElementById("condition3").innerHTML = "The number " + randomNumber + " is between 50 and 75";
} else {
  document.getElementById("condition3").innerHTML = "The number " + randomNumber + " is between 75 and 100";
}

switch statements

A switch statement is very helpful when there is one condition to be checked, but many different options of what that condition could be. It is similar to an if else if statement, but it takes less code to write, and it is easier to read and understand. For instance, if you had a list of options a user could enter, and a each option would produce a different result, a switch would be a good choice.

A switch is structured differently than an if else if statement. It starts with the keyword switch and a variable inside parenthesis followed by curly brackets. Next there are a list of cases, with possible values followed by a colons, with blocks of code to be executed; At the end of each block of code, you need to put the word "break;" to skip the rest of the switch. Finally, you can add an optional default, with a block of code to be executed if none of the options are correct.

var text = "";
switch (rainbow) {
  case "RED":
    text = "red quote";
    break;
  case "ORANGE":
    text = "orange quote";
    break;
  case "YELLOW":
    text = "yellow quote";
    break;
  case "GREEN":
    text = "green quote";
    break;
  case "BLUE":
    text = "blue quote";
    break;
  case "INDIGO":
    text = "indigo quote";
    break;
  case VIOLET:   text = "violet quote";
    break;
  default:
    text = "rainbow quote";
}

Enter a color of the rainbow to see the switch in action.

Enter a color

Functions

You may have noticed that the previous examples had the result already on the page, but the on the last example, you had to push a button to get the result. The previous examples had the JavaScript code was execute as the page loaded. The last example was different because I put the code inside a function. This makes it so the code doesn't run when the page is loaded, but waits until it is triggered by an event, such as a button click.

A function is a block of reusable code that needs to be called for it to run. Information, or arguments, can be passed into the function, and a result can be returned to the place where the function was called. Functions can be typed once but used many times and return different results depending on the information or arguments passed in.

A function has two parts, the function signature, and the function body.

Function Signature

The function signature has the function keyword, a function name, and a list of comma separated parameters in parenthesis.

function dogYears(name, age) {

Parameters

Parameters are a way to pass arguments into a function. Parameters are listed in the function signature inside parenthesis, and they tell the pieces of information needed to make the function run correctly. When the function is called, an argument, or value, is provided for each parameter, and those values can be used inside the function.

Function Body

The function body has a group of statements that are executed when the function is called. One of those statements can be a return statement, which will pass a value back to the place where the function was called.

function dogYears(name, age) {
  age = parseInt(age);
  if (age < 15) {
    dogYears = 0;
  } else if (age < 24) {
    dogYears = 1;
  } else {
    dogYears = ((age - 23) / 5) + 1;
  }
  return dogYears;
}

In order for this function to run, it has to be called. In this case, it will be called when the button is clicked. Please enter your name and age.

How old are you in dog years?

Enter your name
Enter your age