Week 4: Array Methods and Iterators
To Do This Week:
Assignments:
Codecademy: Complete the lessons (not the projects) from the Learn JavaScript module:
- "Iterators"
Decribe your idea and the detailed logic steps for the Interactive Website.
Read (Optional!): Chapters from Eloquent JavaScript:
Upcoming Assignments
- JavaScript Codecademy #1 (DUE Feb 5)
- Interactive Website (5%) (complete with CSS design) (Due Feb 19)
Module Notes
In-class Exercise:
Quick Review: Change Background Color- variables
- click > function
- change CSS
- conditional
- increment
- loop
Changing CSS with JavaScript:
document.body.style.backgroundColor = "lightblue"// change the background color of the whole pagedocument.getElementById("box").style.width = "300px"// set the width of an element with id="box"document.querySelector("h1").style.color = "red"// change the text color of the first <h1>let box = document.getElementById("box"); box.style.border = "2px solid black"// add a border around the elementdocument.querySelector(".demo").style.fontSize = "24px"// change the font size of the first element with class="demo"document.body.style.margin = "0"// adjust the margin of the body (remove default spacing)
Review JavaScript and the DOM:
Traversing // get to elements on the page
-
document.getElementById("bio")
Selects one element by its ID. -
document.getElementsByClassName("stanza")
Selects all elements with a class name (returns an HTMLCollection). -
document.getElementsByTagName("p")
Selects all elements by tag name (like all paragraphs). -
document.querySelector("#bio")
Selects the first element that matches a CSS selector. -
document.querySelectorAll(".stanza")
Selects all elements that match a CSS selector (returns a NodeList). -
element.parentElement
Gets the parent of an element. -
element.children
Gets all child elements inside a parent. -
element.firstElementChild
Gets the first child element. -
element.lastElementChild
Gets the last child element. -
element.nextElementSibling
Gets the next element at the same level. -
element.previousElementSibling
Gets the previous element at the same level.
Creating & Adding Elements // create new elements and add them to the page
-
document.createElement("tag")
Creates a new HTML element (but does not add it to the page yet).// Demo const p = document.createElement("p"); p.textContent = "Hello world"; -
parent.appendChild(element)
Adds a new element inside a parent (at the end).// Demo const div = document.getElementById("output"); div.appendChild(p); -
parent.append(element)
Adds an element (or text) inside a parent.// Demo div.append("More text"); -
parent.prepend(element)
Adds an element to the beginning of a parent.// Demo div.prepend(p); -
element.remove()
Removes an element from the page.// Demo p.remove(); -
parent.removeChild(element)
Removes a specific child element.// Demo div.removeChild(p); -
element.cloneNode(true)
Copies an element (true copies all children too).// Demo const copy = p.cloneNode(true); div.appendChild(copy); -
element.insertAdjacentHTML(position, html)
Inserts HTML directly into the page.// Demo div.insertAdjacentHTML("beforeend", "<p>New paragraph</p>");
Forms: Accessing Values
-
element.value// gets the value of an input, textarea, or select// Demo (text input) const nameInput = document.getElementById("name"); console.log(nameInput.value); -
element.checked// returns true or false (checkbox or radio)// Demo (checkbox) const agreeBox = document.getElementById("agree"); console.log(agreeBox.checked);
JavaScript Methods (in-built functions):
Math Methods:
Math.random()// returns a random number from 0 (inclusive) up to but not including 1Math.round()// rounds a number to the nearest integerMath.floor()// rounds a number DOWN to the nearest integerMath.max()// returns the number with the highest valueMath.min()// returns the number with the lowest valu
Switch vs Conditionals
// Example using switch
let day = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Other day");
}
// Example using else if
let day = 3;
if (day === 1) {
console.log("Monday");
} else if (day === 2) {
console.log("Tuesday");
} else if (day === 3) {
console.log("Wednesday");
} else {
console.log("Other day");
}
Array Methods
-
.split(separator)
Splits a string into an array of substrings.
// Demo const word = "array"; const letters = word.split(""); // ["a","r","r","a","y"] -
.join(separator)
Joins all array elements into a single string.
// Demo ["_","_","_"].join(" "); // "_ _ _" ["c","a","t"].join(""); // "cat" -
.indexOf(value)
Returns the index of the first match, or -1 if not found.
// Demo const tried = ["a","e"]; tried.indexOf("a"); // 0 tried.indexOf("z"); // -1 -
.push(value)
Adds an element to the end of an array.
// Demo const tried = ["o","p"]; tried.push("q"); // ["o","p","q"] -
.pop()
Removes the last element from an array.
// Demo const letters = ["a","b","c"]; letters.pop(); // removes "c" -
.shift()
Removes the first element from an array.
// Demo const letters = ["a","b","c"]; letters.shift(); // removes "a" -
.unshift(value)
Adds an element to the beginning of an array.
// Demo const letters = ["b","c"]; letters.unshift("a"); // ["a","b","c"] -
.includes(value)
Returns true if the value exists in the array.
// Demo const letters = ["c","a","t"]; letters.includes("a"); // true letters.includes("z"); // false -
.slice(start, end)
Returns a portion of an array without changing the original.
// Demo const numbers = [1,2,3,4]; numbers.slice(1,3); // [2,3] -
.splice(start, count)
Removes or replaces elements in an array.
// Demo const numbers = [1,2,3,4]; numbers.splice(1,2); // removes 2 and 3 -
.sort()
Sorts the elements of an array. (Changes the original array.)// Demo (strings) const letters = ["b","a","d","c"]; letters.sort(); // ["a","b","c","d"] -
.sort(compareFunction)
When sorting numbers, you must provide a compare function.// Demo (numbers) const numbers = [10, 2, 30, 4]; // Without compare function (incorrect for numbers) numbers.sort(); // [10, 2, 30, 4] (sorted as text!) // Correct numeric sort numbers.sort(function (a, b) { return a - b; }); // [2, 4, 10, 30]
Array Iterators
-
.forEach(callback)
Runs a function once for each element in the array.
// Demo const letters = ["c","a","t"]; letters.forEach(function (ch, i) { console.log(i, ch); }); -
.map(callback)
Creates a new array by transforming each element.
// Demo const letters = ["a","r","r","a","y"]; const blanks = letters.map(function () { return "_"; }); // ["_","_","_","_","_"] -
.filter(callback)
Creates a new array with elements that pass a test.
// Demo const numbers = [1,2,3,4,5]; const evens = numbers.filter(function (num) { return num > 3; }); // [4,5] -
.find(callback)
Returns the first element that passes a test.
// Demo const numbers = [5,12,8,130]; const big = numbers.find(function (num) { return num > 10; }); // 12 -
.some(callback)
Returns true if at least one element passes a test.
// Demo const numbers = [1,3,5,8]; numbers.some(function (num) { return num % 2 === 0; }); // true -
.every(callback)
Returns true if all elements pass a test.
// Demo const numbers = [2,4,6]; numbers.every(function (num) { return num % 2 === 0; }); // true
forEach() (very useful)
forEach() - w3schoolsforEach() Demo
Interactive Website: 5% DUE: Thursday Feb 19
This assignment is designed to bring together your understanding of basic syntax, variables, conditionals, arrays, functions, and loops in JavaScript. The key objective is to create a dynamic website that allows for user interaction, resulting in changes on the webpage without altering the URL. *In all projects in this class you will include in the source code the natural language steps of your script.Add your commented out ( /*…*/ ) steps in a numbered list inside the <script> tag.Suggested Ideas for Your Website
- Interactive Quiz: A simple quiz where users answer questions, and get immediate feedback.
- Dynamic Photo Gallery: A gallery where users can filter or sort images based on categories.
- To-Do List: A task manager where users can add, mark, and delete tasks.
- Customizable Timer: A timer where users can set and start a countdown for various activities.
- A Digital Art Work: User interactivity creates dynamic displays of image, text, sound and/or video. The weirder the better.
JS Mentor
JS Mentor is a Custom GPT created for this class. Think of it like your personal JavaScript tutor — it helps you learn by guiding you through problems step by step.
Here’s how to get the most out of it:
-
Describe Your Idea
Start by explaining what you want to build or what you're trying to solve — even in plain English. JS Mentor will help you turn that into code. -
Break It Down
JS Mentor will ask you to think through your idea logically: What should happen first? Then what? You’ll write these logic steps in your own words before jumping into code. -
Code One Step at a Time
Once your logic is clear, JS Mentor will help you write one JavaScript statement at a time. You’ll write the code, and it’ll give hints, corrections, or next steps if you get stuck. -
Ask for Help
If you’re stuck, say so! You can ask for a hint, a mini quiz, or even a code example if needed. -
Learn by Doing
Don’t worry about mistakes — JS Mentor is here to help you learn by trying. The more you engage and experiment, the more confident you’ll get.