lecture 4

slides.com/jkohlin/js-4/live

This week: Chapter 4

Till next week: Read chapter 5

Shy? 

Ask a question during lecture

Click here to open form in a new tab

but first, again, what do you know so far?

hoisting

the step where the computer finds all variable declarations first

before any assignments are made

baz = foo;

var foo = 12;
var baz;

//Both foo and baz are 12. 
//This works because of the hoisting step
// After hoisting:
var baz;
var foo;

foo = 12;
baz = foo;

// Hoisting --> You code is rearranged

Arrays

var fruit1 = "apple"
var fruit2 = "banana"
var fruit3 = "cherry"
var fruit4 = "orange"
var fruit5 = "grapes"
var fruit6 = "mango"
var fruit7 = "pear"
var fruit8 = "kiwi"
var fruits = [
  "apple",
  "banana",
  "cherry",
  "orange",
  "grapes",
  "mango",
  "pear",
  "kiwi"]

Many variables

One variable

A mental model of an Array

A storage shelf with numbered spots

Create an empty array

var fruits = [];

Why?

You might want to add stuff to it later, one element at a time.

(I will show you soon)

Create an array with elements

var fruits = ["apple", "banana", "cherry"];
0        1       2

page 128

access an element in an array

var myBanana = fruits[1];
var fruits = ["apple", "banana", "cherry"];
0        1       2

page 129

counting elements in an array

var fruits = ["apple", "banana", "cherry"];
var howMany = fruits.length; // 3

Array.length is a property all arrays have

page 130

Type: Array

A LIST OF MULTIPLE VALUES

var fruits = ["apple", "banana", "cherry"];

var fibonacci = [0, 1, 1, 2, 3, 5, 8, 13];

var conditions = [true, false];

var mixed = ["Everything", 42, true];
Arrays 
(subtype of object)

types

foo = 42;
baz = 3.1415;
foo = "Hello";
baz = 'world!';
foo = true;
baz = false;
foo = true;
baz = false;

NEW!

why use Arrays?

The expandable variable 

// Remember your adventure game inventory?
var inventory = ["sword", "axe", "key"];

// Now you have only one variable instead of:
var inventory1 = "sword";
var inventory2 = "axe";
var inventory3 = "key";
var inventory4 = "";
var inventory5 = "";

// Check number of items: 
if (inventory.length > 3) alert('too many items');

built in functions

...and property

var fruits = ["cherry", "banana", "apple"];
fruits.length == 3 // true

how many elements?

Sort alphabetically

fruits.sort(); // ["apple", "banana", "cherry"];

how to populate an array

1.

2.

3.

//populate it from the start:
var circles = ['green', 'green', 'green', 'green'];
// Built in method push, adds to the end of the array
circles.push('red');
// unshift, adds to the beginning of the array
circles.unshift('red');

4.

//Specify a position 
circles[4] = 'red';

how to remove from an array

1.

2.

3.

// pop removes the last element
circles.pop();
// shift, removes the first element
circles.shift();
// weird quirk
circles.length --

4.

// remove 1 at position 3
circles.splice(3,1); 

a closer look at splice

tricky but useful method

/******************************
  Array.splice(2,1) means:
  Go to index 2, 
  remove 1 item 
  and return it (as an array).
******************************/

var fishes = ["shark", "salmon", "dolphin", "cod"];
var mammals = fishes.splice(2, 1);

/******************************
  fishes: ['shark', 'salmon', 'cod']
  mammal: ['dolphin']
******************************/

a closer look at splice

tricky but useful method

/******************************
  Splice can also
  Remove multiple items and  
  Add new items:
******************************/
var pokerHand = ["Q", "Q", "Q", "J", "8"];
var unwanted = pokerHand.splice(3, 2, "A", "A");
/******************************
  pokerhand: ["Q", "Q", "Q", 'A', 'A']
  unwanted: ['J', '8']
******************************/

how to get all values from an array

even if you don't know how many elements there are

loops

of course

while

var fruits = ["kiwi", "mango", "orange", "banana", "apple"];

var index = 0;

while (index < fruits.length) {

    console.log( fruits[index] );
    index++;

}

...as you know

for

is a compressed form of while

for loop template:

var array = [1,2,3,4];

for ( var i = 0; i < array.length; i++ ) {
    //array[i]
}
  • Open an editor and try to code it without looking
  • LEARN THIS BY HEART

page 140

The Starbucks order

using arrays and push/shift

var orders = [];

function newOrder(item) {
  orders.push(item); // add to bottom
}

function removeOrder() {
  orders.shift(); // remove from top
}

Try it out! 

Add and remove orders too see what happens.

clone an array

// You cannot copy arrays like you do with strings and numbers
x = 10;
y = x;
x = 32;
console.log( x+y ) // 42 not 64

foo = [3,2,1];
bar = foo;
bar.sort();
console.log(foo); // [1,2,3]
console.log(bar); // [1,2,3]


// This is a way to create a copy of an array

foo = [3,2,1];
bar = foo.slice(0);
bar.sort();
console.log(foo); // [3,2,1]
console.log(bar); // [1,2,3]

strings are a bit like arrays

// some array methods apply to strings as well

"hello world".length // 11
"hello world".indexOf("w") // 6


// strings can be converted to arrays .split(separator)

"hello-world".split("-") // ["hello", "world"]
"code".split("") // ["c", "o", "d", "e"]

// Access a letter from a string
var foo = "hello world";
var bar = foo[6]; // "w"

Array properties and methods

var fruits = ["kiwi", "mango", "orange", "banana"];

fruits.length 
// 4 (returns the amount of elements)

fruits.indexOf("kiwi") 
/* search for the index of a specific value
0 (If the argument passed in doesn't exist,
   -1 is returned. If two exist, the first is returned) */

fruits.reverse() 
// reverses the order of the elements
// ["banana", "orange", "mango", "kiwi"]

fruits.sort();
// sorts alphabetically (even numbers are sorted alphabetically)
// ["banana", "kiwi", "mango", "orange"]

fruits.splice(2, 1) 
/* starts deleting elements from index 2 (orange) 
   and deletes one (1) item. 
   The deleted item(s) is returned as an array */

concat

combining two arrays

/******************************
  Array.concat() -Combine Two Arrays
******************************/
var pair = ["J", "J"];
var threeOfAKind = ["9", "9", "9"];
var fullHouse = pair.concat(threeOfAKind);
/******************************
 pair:         ['J', 'J']
 threeOfAKind: ['9', '9', '9']
 fullHouse:    ['J', 'J', '9', '9', '9']
******************************/

finding things in the dom

2# Find the Element By searching for its CSS selector

document.querySelector("#main-menu") 
// <nav id="main-menu">...</div>
<header>
  <nav id="main-menu"> <!-- this and all it's children -->
    <ul>
      <li>home</li>
      <li>about</li>
    </ul>
  </nav>
</header>

document.querySelector() returns the element that match the argument passed in.

change the content of an element

<div id="demo">
<h1>Existing content</h1>
</div>
var div = document.querySelector('#demo');

div.innerHTML = '<p> This is <em>new</em> content </p>';

Existing content

This is new content

 

<div id="demo">
<p> This is <em>new</em> content </p>
</div>

HTML

HTML

Browser output

Browser output

Using innerHTML

Lecture 4 - Arrays

By Johan Kohlin

Lecture 4 - Arrays

  • 978