JavaScript with Sean Doyle

Lesson 3: Arrays & Loops

Arrays

The Big 5 Concepts

  1. An array lets us track multiple values with one variable. In JavaScript, an array can store mixed data types, and can store other arrays and objects.
  2. An array has numbered spots where it stores items. We use this number (its “index”) to store and retrieve values.
  3. The index starts at 0 (as most numbering does in computer programming).
  4. The number of items in an array is referred to as its “length”.
  5. Arrays have their own built in functions (“methods”) that can modify or copy an array.

Code Samples

//In JavaScript, the square brackets indicate an array.
    
var myThings = []; //creating an empty array.
var myBooks = ["The Joy of Code", "Oh, the Places You'll Go"];
var myOtherBooks = [book1, book2, book3, book4]; //storing variables in an array.
    
//Retrieve values with the name of the array, and the item's index number (start counting at 0).
var myBook = myBooks[1];  //Oh, the Places You'll Go

Loops

The Big 5 Concepts

  1. A loop is a block of code that can run multiple times to complete a repetitive task.
  2. The code inside the code block of the loop will execute with each iteration of the loop.
  3. Loops need to know when to start and when to stop – otherwise they will become infinite loops! You set the start value and the running condition to control this.
  4. Once the running condition for the loop has been met, the program will carry on with the next line of code that comes after the code block of the loop.
  5. The two main types of loops to understand are:
    • the for loop. This “incrementor” or “counter” loop runs a set number of times. Also, good for looping through an array.
    • the while loop. This loop is watching for a condition to change – and we don't know how many iterations that will take.

Code Samples

//The structure of a for loop...
for (start; condition; increment) {
    //Code to repeat each time.
    //More code to repeat each time.
}

//A basic for loop...
for (var i = 0; i < 10; i = i + 1) {
    console.log("The value of i is now: " + i);
    //Above, we are using the incrementor variable within the loop.
}


//The structure of a while loop...
while (this condition is true) {
	//Code to repeat each time.
	
	//Something needs to change the running condition in the code block!
}

//A basic while loop...
var isValid = false;//Starting value is the value of this outside variable.

while (isValid === false) {
	console.log("It's not valid.");
	
    var confirmCheck = confirm("Valid?");
    
    if(confirmCheck === true){ //This logic will change the value of isValid, thus, ending the loop.
        isValid = true;
    }
}