Week 7 | March 21, 2016

Arrays, Objects & Loops

Lesson Prep

  • Open: Class Website (Week 7)
  • Open your website in sublime
  • Start a new directory in your website called arrays-and-objects.
  • In arrays-and-objects create an index.html file and paste in the markup below:
    <!DOCTYPE html>
    <html>
    <head>
      <title>Week 7 - Arrays, Objects and Loops</title>
    </head>
    <body>
      <h1 id="headline">Storing Data in JavaScript</h1>
      <ul id="list"></ul>
    </body>
    </html>

Definitions / HW Review

Remember Variables?

  • A variable remembers a value that you've assigned to it.
  • For example var x = 102.
  • When we say "store a value" it means we are assigning it to a variable for later use or "creating a reference" to it.

Object

Essentially, everything in JavaScript is an object. You can create object when you need to store multiple variables to a particular place.

Property

A variable that provides information about an object. Needs to be paired with a value.

Array

A way of assigning multiple values to one variable.

Loop

Allows you to "loop through" each object in an array and perform a function on each.

Arrays

An array is a way of assigning a series of values to a single variable. Each object in an array is separated by commas.

Examples

  • var x = [100, 454, 900, 128934, 2];
  • var fruits = ["orange","grape","apple","strawberry"];

Array Index

Each object in an array is assigned an index value, starting with 0.

  • 0 = orange
  • 1 = grape
  • 2 = apple
  • 3 = strawberry

Length

You can use the length property of an array to see how many items are in it. For example: arrayName.length;

Or using the array from the previous example, fruits.length, which will return 4.

Accessing an Item

To grab an item from an array, you simply need to refer to the variable holding the array, and then the item's index.
var myFruit = fruits[2];

Exercise

  • On your index page, create an array of five objects. Use book titles (a string of text)
  • Store your array in a variable
  • Log the variable so you can see it in your console using console.log();
  • Log the value of the third item in the array.

Objects

A way of storing multiple pieces of information in a single place.

Storage

When storing variables to an object, you need to specify both the property and its value.

Examples

  • weddingGuest = {
       name:"John Doe",
       age:"42",
       meal:"chicken"
    };
  • You can access any object property through the dot syntax: weddingGuest.name

Object Methods

An object can also contain a function that let's you interact with the object's properties. This is called a method.

Method Examples

myCountry = {
   getCapital: function() {
      alert(this.myCapital);
   },
   myName: "USA",
   myCapital: "Washington, D.C."
};


To call this method: myCountry.getCapital()

Everything is an Object

Essentially everything in javascript and jQuery is an object.

Arrays, functions, elements, strings, etc. And every element has properties and methods.

Exercise

  • Create your own object on your index page with three different properties and store in a variable called book. Use your favorite book and define the title, author, genre

  • Log the variable so you can see it in your console
  • Log one property so you can see it in your console.

Arrays & Objects

Arrays and objects can be part of each other. You can have an array of objects, and arrays can be values in objects.

Example

var books = [
  {
    title: The Thornbirds,
    author: Colleen McCullough,
    genre: Fiction
  },
  {
    title: The Price of Inequality,
    author: Joseph Stiglitz,
    genre: Economics
  },
];

The for Loop

A way of cycling through an array and performing an action on each object.

Types

There are multiple types of loops, and using other JavaScript frameworks, multiple ways of performing them. We will focus today on the for loop, as it will likely be the most used and is the basis for the each method in jQuery.

Loop Parts

Each loop has four parts that need to be defined

  • Initialization: Takes place once at the start of the loop
  • Test condition: Checks the variable to see if the loop should stop or keep going
  • Action: The code that is repeated as we go through the loop
  • Update: Updates the variable being used by the test condition to see if we should keep going

For Loops

myArr = ["one","two","three","four"];

for ( var i=0 ; i < myArr.length ; i++){
   alert(myArr[i])
}

Lowercase i

In JS, the lowercase i represents the index of an object in an array. In loops, we use i to represent each index.

Exercise

  • Write a for loop that goes through your list of books created during the array exercise.
  • Log books[i] to see each instance of the loop.
  • Append each book to the page.
  • Use the innerHTML property to change the headline of the page (Google it if you don't know!) to My Favorite Books.

a few more concepts...

...before we build our first application.

The return Statement

A return statement determines the value the function produced or returns. return passes an object to the code that called your function.

In your function, say return variableName; to define what you want to pass back to your original code.

JavaScript Operators

Used to assign values, compare values, perform arithmetic operations, and more. You've already use them to define variables and to concatenate strings. You can also add (+), subtract (-), multiply (*) and divide (/) numbers using usual arithmetic rules and order of operations.

Read more about operators here »

The Math object

To perform further mathematical operations on numbers, JavaScript has a number of Math operations available, which allow you to round numbers, find the largest or smallest number in an array or return a random number.

Example: Math.max(12,35,5,67,22.3,9); will return 67.

Read more about Math operators here »

NaN

Stands for Not-A-Number in JavaScript. You may see this returned on one of your Math or arithmetic operations, indicating that you are working with variables that aren't numbers, and which can't be operated on.

You can also evaluate the value of variable to check if it is a number or not, using isNaN();.

Read more about NaN here »

The Tip Calculator & git

clone Tip Calculator Files

You can find them on my GitHub page.

Remove origin and init new repo

  • git remote remove origin
  • git remote -v should return nothing
  • git init

When you're finished

add/commit/push

your new Tip Calculator

Assignment

Reading

  • Read in JavaScript&JQuery, Chapter 3-4

Codecademy

  • Do Codecademy's Arrays & Objects lesson exercises 1-4 and 9-13 and screenshot lessons 4 and 13.
  • You should upload two screenshots to Dropbox to show that you've complete the exercises.
  • Add Reset Function to Tip Calculator

    • Add a button in index.html that users can push to "reset" or "calculate another tip"
    • The button will need an onclickattribute to call another function in your code.
    • Write a function that goes through each element on the page and resets it to the initial state.
    • Make sure you add, commit, push when you are finished.