Front End Web Development

Spark Boulder, Summer 2017

Session 12: Into Darkness

Javascript 103: objects and arrays

More Dumb Fun Web Dev Stuff

http://benhowdle.im/beattheclock/

Holy crap, this thing is difficult.

It's a great thing to aspire to beat!

Project 3: Coin Flipping App

For your third project, I'd like you to create an app that flips a coin and records the results!

I'd like for you to create a page with two buttons: "Flip coin" and "Reset". Every time you click the "Flip coin" button, your page writes either a "Heads" or "Tails" to the page. Every time you click the "Flip coin" button, the old results stick around, so eventually you'll have a big long list of "Heads" and "Tails".

If you click the "Reset" button, it should clear out all the previous results, and allow you to click the "Flip coin" button for more results.

I should also mention, there should be a 50/50 chance for heads/tails :)

A couple things:

MOAR JAVASCRIPT

⌘-T (or ctrl-T) -> fuzzy file finder!

Arrays

What if we needed to store a list of all the cars that you've driven?

We wouldn't want to do something like this:

var kensFirstCar = "1985 Pontiac Fiero";
var kensSecondCar = "1998 Honda Accord";
var kensThirdCar = "1999 Subaru Outback";
var kensFourthCar = "2000 Subaru Impreza 2.5RS";

If I wanted to console.log() all of the cars I owned, I'd have to do something like:

console.log(kensFirstCar);
console.log(kensSecondCar);
console.log(kensThirdCar);
console.log(kensFourthCar);
// etc...

What if I had driven 100 cars? That would get pretty ugly pretty quick.

So, we're going to store all the cars that I've driven in an Array. You can also think of an Array as a list!

Creating Arrays

Here's how we would create an Array:

var kensCars = ["1985 Pontiac Fiero", "1998 Honda Accord", "1999 Subaru Outback", "2000 Subaru Impreza 2.5RS"];

I could also put line breaks between all the elements:

var kensCars = ["1985 Pontiac Fiero",
                "1998 Honda Accord",
                "1999 Subaru Outback",
                "2000 Subaru Impreza 2.5RS"];

Then, what happens when we do console.log(kensCars);?

Reading the contents of Arrays

What was the first car that I drove? I forgot.

Oh good! I can just look at the first element of the kensCars array to find out.

I can log out the first element of the kensCars array like this:

console.log(kensCars[0]);

Notice that in order for us to get the first element of the array, we have to use a 0 instead of a 1!

A more technical way to say this would be "the element at index zero". An index is sort of like an "address" for an array, like the floors of a (european?) building.

So, kensCars[0] references the first element of the kensCars array, kensCars[1] references the second element of the array, kensCars[2] references the third element, and so on.

What happens if we try to access kensCars[4]?

Did you know that Ken used to wear a puka shell necklace? We'd like to forget that too.

Iterating through Arrays

What are all of the cars that I've driven? I forgot.

I could do something like this...

console.log(kensCars[0]);
console.log(kensCars[1]);
console.log(kensCars[2]);
console.log(kensCars[3]);
// etc...

...but what would happen if I had driven 100 cars?

Screw that noise! Notice how we're just incrementing which index we're looking at every time we log something?

Let's just use a loop!

Properties of Arrays

...but wait. If we want to use a loop to print out all of the cars that I've driven, we at least need to know how many cars I've driven.

So, we can use the length property of our array.

console.log(kenCars.length);

But wait...this logs out 4. That's correct, right? Our array has four elements. But the fourth element actually resides at index 3.

Which leads to the two hard things in computer science:

"There are two hard things in Computer Science: cache invalidation, naming things, and off-by-one errors."

Wrapping up our for loop:

for (var i = 0; i < kensCars.length; i++) {
    console.log(kensCars[i]);
}

Modifying Arrays

Ah crap, I forgot that my first car was a 1984 Pontiac Fiero, not a 1985 Pontiac Fiero.

That's alright! I already know that it's my first car, so I can just replace the element at index 0.

console.log(kensCars[0]);
kensCars[0] = "1984 Pontiac Fiero";
console.log(kensCars[0]);

Now, let's say that the Tesla Model 3 waitlist suddenly jumps 200,000 people or so, and I take delivery of mine next week. Looks like I have to add another car to the list!

I could just create a new item at the end of the list, like this:

kensCars[4] = "2017 Tesla Model 3";

CS people take note - I don't actually have to allocate space for new array elements! I could also set something at kensCars[100] and it would work just fine D:

But, what if you don't know where the array ends? You could do something like this...

kensCars[kensCars.length - 1] = "2017 Tesla Model 3";

...but I'm remembering something about off-by-one errors, and I think there's got to be a better way.

Adding items to Arrays, and other Array methods

The easiest way to add something to the end of an array is .push().

console.log(kensCars);
kensCars.push("2017 Tesla Model 3");
console.log(kensCars);

Hooray!

There's lots of other methods that make it easier to work with Arrays. Explore and enjoy!

Objects

Alright, so we know all of the cars Ken has driven over the years, but we don't really know much about them.

What if we only wanted to see cars that have automatic transmissions? Or cars that were painted white? We don't really know anything about that based off of "1984 Pontiac Fiero".

We're going to use objects to represent our cars now! Objects are basically like variables that can contain other variables.

Creating Objects

Let's create a "car" object!

var kensCurrentCar = {
    year: 2000,
    make: "Subaru",
    model: "Impreza 2.5RS"
}
console.log(kensCurrentCar);

Objects are composed of keys and values. year is a key, and the number 2000 is a value.

Notice that we need to have a comma after every key/value pair.

Reading the contents of Objects

What year is my car again? I forgot.

Let's check the year key on kensCurrentCar!

console.log(kensCurrentCar.year);

Hey, we can build a nice little summary string based off of the keys and values of my car!

console.log(kensCurrentCar.year + " " + kensCurrentCar.make + " " + kensCurrentCar.model);

Modifying objects

Hm. I wanted to put color and transmission type on my car too!

We can set the keys of our objects just like variables!

console.log(kensCurrentCar);
kensCurrentCar.color = "red";
kensCurrentCar.transmission = "manual";
console.log(kensCurrentCar);

Using Chrome's Dev tools? The stuff logged to the console might not look correct, because chrome reads the contents of the object as soon as you click the little arrow.

Putting it all together - an exercise for the reader

Given that I have an array of my cars, like this:

var kensCars = [{
    year: 2017,
    make: "Tesla",
    model: "Model 3",
    color: "red",
    transmission: "automatic"
}, {
    year: 2000,
    make: "Subaru",
    model: "Impreza 2.5RS",
    color: "red",
    transmission: "manual"
}, {
    year: 1999,
    make: "Subaru",
    model: "Outback",
    color: "green",
    transmission: "automatic"
}, {
    year: 1998,
    make: "Honda",
    model: "Accord",
    color: "white",
    transmission: "manual"
}, {
    year: 1985,
    make: "Pontiac",
    model: "Fiero",
    color: "white",
    transmission: "automatic"
}]

Can you log out only the cars with manual transmissions? What about the ones painted white? What about logging out all of them, sorted by oldest to newest?

Lightning round!

Let's write out all of the cars to the page!

<!-- index.html -->

<h1>Ken's Cars</h1>
<div id="cars"></div>

<script src="myscript.js" charset="utf-8"></script>
// myscript.js

for (var i = 0; i < kensCars.length; i++) {
    var newCarHTMLElement = document.createElement("p");
    newCarHTMLElement.innerHTML = "a " + kensCars[i].color + " " + kensCars[i].year + " " + kensCars[i].make + " " + kensCars[i].model + " with a " + kensCars[i].transmission + " transmission";
    document.getElementById("cars").appendChild(newCarHTMLElement);
}

That's all I've got for today!

What questions are there?

How to be a Web Developer

  1. Look stuff up on the internet
  2. Make stuff
  3. Repeat

Excelsior! 🚀