Arrays and Loops

pre-lecture bonus topic

Adding elements to the DOM using JavaScript

(or adding HTML tags to the page using JavaScript)

   const mySection = document.createElement("section");
   mySection.textContent = 'Hello, World'
   document.querySelector(".container").appendChild(mySection)
    

creates the element

tag of the new element

selector for parent

Adds the element to the DOM

The new element

Loops

Loops allow us to do the same task repeatedly a controlled amount of times. 

Use Cases:

- I want to count from 1 to 100 and print out all the even numbers

- While my hand of playing cards totals less than 21, draw a card

- disable all the buttons on the page

 

For loops

for (COUNTER; TILL WHEN; CHANGE COUNTER){

}


// print out the numbers 0-9
for( let i = 0; i <= 9; i++) {
    console.log(i)
}

For loops example

// Count the numbers 1-100, 
// if the number is /5 then put in the DOM

for(let i = 1; i <= 100; i++){
    if (i % 5 == 0){
        const newSpan = document.createElement("span");
        newSpan.textContent = i
        document.querySelector(".list").appendChild(newSpan)
    }
}

While loops

While Definition

while (some_truthy_expression){
    // do something
}

While Example

let isNightTime = lookOutsideForSun()

while (isNightTime){
    // do something
    sleep(oneHour)
    isNightTime = lookOutsideForSun()
}

Array

Types so far

// Number
const count = 5; 

// string
let dayOfWeek = "Tuesday";

// function
const updateButtonEvent = () => {
    console.log("button clicked")
}

// boolean
const isCool = true

Arrays are a data structure that allows us to store things in a list-like manner 

Before array

const lion1Name = "Simba";

const lion2Name = "Scar";

const lion3Name = "Nala";

const lion4Name = "Mufasa";

With Arrays

const lions = ["Simba", "Nala", "Scar", "Mufasa"]

console.log(lions[2]) // what will this print out?

Using arrays

const myFavoriteThings = []

// add
myFavoriteThings.push('Raindrops on roses')

myFavoriteThings.push('whiskers on kittens')

// add and update
myFavoriteThings[5] = 'Bright copper kettles'

// delete

myFavoriteThings.splice(5,1);

bringing it all together

 

const disneyVillains = ["Jafar", "Scar","Hades", "The Shadow Man"]

for (let i= 0; i < disneyVillains.length; i++){
    const listItem = document.createElement('li')
    listItem.textContent = disneyVillains[i];
    document.querySelector('.villains').appendChild(listItem)  
}

But wait! there is more....

Really bringing it together

 

const disneyVillains = ["Jafar", "Scar","Hades", "The Shadow Man"]

for (let i= 0; i < disneyVillains.length; i++){
    const currentVillain = disneyVillains[i];
    const listItem = document.createElement('li')
   
    if (currentVillain === "Hades"){
         listItem.classList.add("under-appreciated-villain") 
    }
    listItem.textContent = currentVillain;
    document.querySelector('.villains').appendChild(listItem)  
}

lets build something.

Made with Slides.com