function myFunction() {
alert("hello");
}
myFunction();
// calls the function once
function addition(a, b) {
return a + b;
}
console.log(addition(1, 2));
function addition(a, b=10) {
return a + b;
}
console.log(addition(9));
console.log(addition(9, 3));
const myAddition = (a, b = 10) => {
return a + b;
}
console.log(myAddition(9));
const oneLiner = (a, b) => a + b;
console.log(oneLiner(12, 5));
const noParam = () => {
console.log("hello");
}
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
// Note console.log is a function
repeat(3, console.log);
function greaterThan(n) {
return m => m > n;
}
let greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
let labels = [];
repeat(5, i => {
labels.push(i);
});
console.log(labels);
// [ 0, 1, 2, 3, 4 ]
index.html
from the last class activity
nodeHTML)document.querySelector returns
null if no match// first element matching a class
document.querySelector(".myclass");
// by id
document.querySelector("#log");
/* first element with
- with the name "login"
- located inside a `<div>`
- with the class `user-panel main`
*/
document.querySelector(
"div.user-panel.main input[name='login']"
);
querySelectorAll()
returns all matching nodes as an arrayconst link = document.querySelector("a");
link.textContent = "HCDD 340";
link.href = "https://hcdd-340.github.io/"
para.style.color = "white";
para.style.backgroundColor = "black";
para.style.padding = "10px";
para.style.width = "250px";
para.style.textAlign = "center";
this?this points to
current objectconst person = {
// …
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
this points to
current objectconst person1 = {
name: "Chris",
introduceSelf() {
console.log(`Hi! I'm ${this.name}.`);
},
};
const person2 = {
name: "Deepti",
introduceSelf() {
console.log(`Hi! I'm ${this.name}.`);
},
};
What will happen for person1.introduceSelf()?
person.age = 45;
person["name"]["last"] = "Cratchit";
const objectName = {
member1Name: member1Value,
member2Name: member2Value,
member3Name: member3Value,
};
const person = {
name: ["Bob", "Smith"],
age: 32,
bio() {
console.log(`${this.name[0]} is ${this.age} years old.`);
},
introduceSelf() {
console.log(`Hi! I'm ${this.name[0]}.`);
},
};
person.age;
person.bio();
Using dot
person["age"];
person["name"]["first"];
Using bracket
addEventListener()const button = document.querySelector("button");
button.addEventListener("click", (event) => {
console.log("clicked!")
console.log(event);
});
main.js (see hints on line 23–27)
chooseCollege
colleges<h4> with the selected itemsconst button = document.querySelector("button");
button.addEventListener("click", (event) => {
console.log("clicked!")
console.log(event);
});
const button = document.querySelector("button");
button.addEventListener("click", (event) => {
console.log("clicked!")
console.log(event);
});
What do you see in Console?
button.addEventListener("click", (event) => {
event.target.style.color = "purple";
console.log(event);
});
target points to source of the event
Programs can only do one-thing at a time
Long-running tasks will block interactions
When the task is completed, it will be called with the result
Conceptually, similar to event handling
PromiseProxy for values not necessarily known yet
3 possible states in a Promise
Promisethen method,
which allows attaching functionsonSuccessonErrorfetch API streamlines these steps
PromisefetchPromisethen function to:
fetchfunction onSuccess(response) {
console.log("Success!" + response.status);
}
function onError(error) {
console.log('Oh no! Error: ' + error);
}
fetch('hcdd-340.txt')
.then(onSuccess, onError)
fetchHTTP error code (e.g., 402)file:/// protocol does not allow network accessonError is calledfetchHTTP error code (e.g., 402)onSuccess is called (even when it is HTTP error
code)const url = "colleges.json"
const fetchPromise = fetch(url);
console.log(fetchPromise);
fetchPromise.then((response) => {
console.log(`Received response: ${response.status}`);
});
fetchPromise
// if successful, then get `json` data
.then((response) => response.json())
.then((data) => {
console.log(data[0].name); // `then` for second promise
});
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
console.log(data[0].name);
})
.catch((error) => {
console.error(`Unable to fetch: ${error}`);
});
main.js handles error (.catch ...)main.jsmain.jsthen in a
Promise takes two functionsasync and awaitInstead of using then() method
async function getData() {
const url = "colleges.json"
const response = await fetch(url);
console.log(`Received response: ${response.status}`);
}
async and
awaitasync function getData() {
const url = "colleges.json"
const response = await fetch(url);
console.log(`Received response: ${response.status}`);
}
async marks that it is an asynchronous function
async and
awaitasync function getData() {
const url = "colleges.json"
const response = await fetch(url);
console.log(`Received response: ${response.status}`);
}
await will cause the function to ‘freeze’ till the
Promise is resolved
async and
awaitconst url = "colleges.json"
const fetchPromise = fetch(url);
fetchPromise
.then((response) => response.json())
.then((data) => {
console.log(data[0].name);
});
==
const getData = async () => {
const url = "colleges.json"
const response = await fetch(url);
const data = await response.json()
console.log(data[0].name)
}
async and
awaitconst getJson = async (url) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Error! ${response}`)
}
const data = await response.json()
console.log(data[0].name)
return data;
}
// Calling it from another `async` function
try {
let colleges = await getJson("colleges.json");
} catch(error) {
console.error(error);
}
main.jsmain.jsasync and await