General Assembly

Arrays and Loops

Wilson Espina

Review

What did we do last lesson?

Arrays and Loops

Exit Ticket Questions

  1. Can I get more help with the installation?

Arrays and Loops

Learning Objective

Learning Objectives

At the end of this class, you will be able to:

  • Run JavaScript in the Browser.
  • Create arrays and access values in them.
  • Build iterative loops using for statements.
  • Iterate over and manipulate values in an array.

Arrays and Loops

Agenda

  • Classroom Resources
  • JavaScript in the Browser
  • Arrays
  • Loops
  • Array Iterators

Arrays and Loops

Classroom Resources

Arrays and Loops

Create a JSD classroom folder

  • Create a directory called JSD on your machine.
  • A suitable place would be in your Documents folder: ~/Documents/JSD
Github Enterprise step 0

Arrays and Loops

Pull from Github Enterprise

Head to : https://git.generalassemb.ly/wilson-espina/jsd-9-resources

Github Enterprise step 1

Arrays and Loops

Pull from Github Enterprise

  • Click on 'Clone or Download'
  • Make sure the Heading says 'Clone with HTTPS'
  • Select the Clipboard item to to copy the URL
Github Enterprise step 2

Arrays and Loops

Clone JSD-9 Resources locally

  • cd into your JSD folder
  • Type git clone
  • Paste the URL you just copied from Github Enterprise and hit return. This should clone the repo into your JSD folder
Github Enterprise step 3

Arrays and Loops

JavaScript in the Browser

Arrays and Loops

Chrome Console

Access by pressing cmd + alt + j

Chrome dev tools
  • JavaScript can be run directly in the console
  • Useful to write and execute code quickly

Arrays and Loops

Debugging

Chrome dev debugging tools
  • Error messages can be useful when debugging code.
  • Often verbose in saying what the mistake is and on which line.

Arrays and Loops

Debugging

Google is your friend - Don't be afraid to Google JavaScript methods or syntax.

Google screenshot

Arrays and Loops

Google Search Terms

Google search terms examples
  • Always include the programming language and key terms.
  • Questions can be similar to how you would ask a person.

Arrays and Loops

Useful Resources

  • Stack Overflow
  • Mozilla Developer Networks (MDN)
  • W3Schools
  • Medium Articles
  • Blogs
Stack Overflow logo Mozilla Development Network logo W3Schools logo

Arrays and Loops

Arrays

Arrays and Loops

Arrays

  • An array acts like a list.
  • Array items are separated by commas.
  • Arrays are enclosed by square brackets [ ]
Array example 1

Arrays and Loops

Arrays

  • Each item in an array is called an element.
  • Elements can be any data type.
Array example 2

Arrays and Loops

Array Index

  • Each array element is assigned an index, which is a number used to reference that element.
  • Index starts at 0
Array example 3

Arrays and Loops

Array Index

  • The final index value is always the length of the array minus 1.
Array example 4 Array length example

Arrays and Loops

Length Property

  • length property is a number 1 greater than the final index number.
  • length !== number of elements in the array.
Array example 4 Array length example 2

Arrays and Loops

Getting values from an Array

  • Array index starts from 0

let a = ['dog', 'cat', 'hen'];
undefined

a[0];
"dog"

a[1];
"cat"

a[2];
"hen"
						
  • array.length isn't necessarily the number of items in the array
  • 
    a[100] = 'fox';
    a.length; // 101
    						

Lab - Arrays Loops Section 1

Exercise

Key Objective

  • Understand how to use and apply Array methods

Type of Exercise

  • Individual

Location

  • starter-code > 0-arrays-loops-exercise

Timing

8 mins

  1. In the app.js file, complete questions 1-4.
  2. Note that most of your answers should be stored in variables called q1, q2 etc., and the variables printed to the console. See Question 0, which is already completed, for an example.
  3. You will work on the remaining questions later in class today.

Arrays and Loops

Array Helper Methods

Arrays and Loops

Array Helper Methods

Method Use
toString()

Returns a single string consisting of the array elements converted to strings and separated by commas

join()

Same as toString(), but allows you to pass a custom separator as an argument

concat()

Merges two or more arrays together

pop()

Removes and returns the item at the end of the array

push(item1, …, itemN)

Adds one or more items to the end of the array

reverse()

Reverses the array

shift()

Removes and returns the item at the start of the array

unshift(item1, …, itemN)

Adds one or more items to the start of the array

Code along

Code Along

Open up: 1-loops-codealong

Arrays and Loops

Loops

Arrays and Loops

Iteration

Iterating is a way of incrementally repeating a task, one at a time.

Stacking cat

Arrays and Loops

While

while is a loop statement that will run while a condition is true

  • While loops are good for basic looping, but there's a possibility it will never get run

while (true) {
// an infinite loop!
}
							
  • This would cause a Browser to break

Arrays and Loops

Do-While

Using a do-while loop makes sure that the body of the loop is executed at least once.

  • while() isn't evaluated until after the block of code runs.

let input = 0;
do {
  console.log(input++);
} while (input < 10);
							

Arrays and Loops

While Loop

It is possible to iterate over an array with a while loop:


let a = [1, 2, 3, 4, 5]
let len = a.length;
let i = 0;

while(i < len) {
  console.log(i);
  i++;
}
							

Arrays and Loops

For Loop

You can also iterate over an array with:


let teams = ['Liverpool', 'Arsenal', 'Chelsea'];

for (let i = 0; i < teams.length; i++) {
	console.log(teams[i]);
}
// Liverpool
// Arsenal
// Chelsea
							
For statement

Lab

Exercise

Type of Exercise

  • Individual

Location

  • starter-code > 2-loops-exercise

Timing

10 mins

  1. Write code that creates a for loop that calculates 2 to the 10th power, and console.logs each step of the calculation.
  2. BONUS 1: Rewrite your code to allow a user to enter the exponent value, rather than hard-coding it into your program. (Hint: Read up on the window.prompt method.)
  3. BONUS 2: Rewrite your code to use a while loop rather than a for loop.
  4. BONUS 3: Rewrite your code to use a do/while loop rather than a for loop or while loop.

Arrays and Loops

Array Iterator Methods

Arrays and Loops

forEach Loop

Another way of iterating over an array that was added with ECMAScript 5 is forEach():


let teams = ['Tottenham', 'QPR', 'Watford'];

teams.forEach(function(element)) {
  console.log(element);
};
							
For each statement

Lab - Arrays Loops Section 2

Exercise

Type of Exercise

  • Individual / Pair

Location

  • starter-code > 0-arrays-loops-exercise

Timing

6 mins

  1. In the index.js file, complete questions 5-6.
  2. As in the section you did earlier, your answers should be stored in variables called q1, q2 etc., and the variables logged to the console.
  3. Answer these questions using forEach() loops, not for loops.

Arrays and Loops

Array Iterator Methods

Method Use
forEach()

Executes a provided function once per array element

every()

Tests whether all elements in the array pass the test implemented by the provided function

some()

Tests whether some element in the array passes the text implemented by the provided function

filter()

Creates a new array with all elements that pass the test implemented by the provided function

map()

Creates a new array with the results of calling a provided function on every element in this array

Code along

Code Along

Open up: 3-array-iterators-codealong

Lab - Arrays Loops Section 3

Exercise

Type of Exercise

  • Individual / Pairs

Location

  • starter-code > 0-arrays-loops-exercise

Timing

5 mins

  1. In the index.js file, complete question 7.
  2. As in the section you did earlier, your answer should be stored in a variable called q7 and the variable logged to the console.

Lab - Putting it all together

Exercise

Type of Exercise

  • Individual / Pairs

Location

  • starter-code > 4-arrays-loops-exercise-2

Timing

Until 20:45

  1. Write code for a website shopping cart that calculates the sales tax for each item in a cart array and stores the result in a 2nd array.
  2. Calculate the total with tax of all cart items and store the result in a new variable.
  3. BONUS: Update your code to round each item to the nearest penny. (Hint: Read up on Math.round).
  4. BONUS: Rewrite your code to use the Array.map method.

Arrays and Loops

Learning Objectives - Review

  • Run JavaScript in the Browser
  • Create arrays and access values in them
  • Build iterative loops using for statements.
  • Iterate over and manipulate values in an array.

Arrays and Loops

Q&A

Arrays and Loops

Exit Ticket

(Lesson 03)