Skip to content
Snippets Groups Projects
Commit b82f1c02 authored by Andrej Rasevic's avatar Andrej Rasevic
Browse files

adding week1 lecture slides and code examples

parent 7347d04c
No related branches found
No related tags found
No related merge requests found
Showing
with 734 additions and 0 deletions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Adding Properties</title>
</head>
<body>
<script>
"use strict";
let sale = {};
do {
let item = prompt("Enter name of item you want to buy.");
let numberOfItems = Number(prompt("Enter number of items you want to buy"));
/* Adding property */
if (sale[item] === undefined) { // IMPORTANT: Otherwise will remove previous value
sale[item] = numberOfItems;
} else {
sale[item] += numberOfItems;
}
if (!window.confirm("Do you want to buy another item?")) {
break;
}
} while (true);
/* Report about bought items */
let report = "Items bought\n";
for (let propertyName in sale) {
report += propertyName + "-->" + sale[propertyName] + "\n";
}
alert(report);
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Destructuring Example</title>
</head>
<body>
<script>
"use strict";
main();
function main() {
/* Destructuring arrays */
let names = ["Andrew", "Karl", "Olivia"];
let [first, second] = names;
document.writeln("Original Array: " + names + "<br>");
document.writeln("First: " + first + "<br>" + "Second: " + second + "<br><br>");
document.writeln("***** Destructuring Object *****<br>");
/* Destructuring object */
let app = {
name: "mapApp",
developed: 1986,
location: "CP"
};
/* You must use the same property name; try name2 instead of name
You don't need to retrieve all properties (convenient for objects
with several properties)
*/
let {
name,
developed
} = app; /* Notice using { } */
document.writeln("Name: " + name + ", " + "Developed: " + developed + "<br><br>");
document.writeln("***** Destructuring Object in Function Call *****<br>");
myFunc(app); /* function call */
function myFunc({developed}){
document.writeln("In Function: developed: " + developed + "<br><br>");
}
document.writeln("***** Destructuring Object in Function Call *****<br>");
/* function call */
myFunc2(app);
/* Using a property name different than original */
function myFunc2({name: yourName}){
document.writeln("YourName: " + yourName + "<br><br>");
}
document.writeln("***** Swapping Values *****<br>");
/* swap */
let a = 100,
b = 200;
[b, a] = [a, b];
document.writeln(a + ", " + b + "<br>");
}
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script>
process();
async function process() {
let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end
alert(`Retrieving data from ${url} (check console for results)`);
const response = await fetch(url);
console.log("Response");
console.log(response);
const json = await response.json();
console.log("Json");
console.log(json);
console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console
}
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>TAs Info</title>
</head>
<body>
<h3>CORS</h3>
<p>
Try running this example by first opening this file using Live Server and
then by right-clicking on the file and selecting the Chrome browser.
</p>
<div id="display"></div>
<script>
async function readTAsInfo() {
const filename = "./tas.json";
const response = await fetch(filename);
const data = await response.json();
let table = "";
data.forEach((entry) => {
table += `<tr><td>${entry.name}</td><td>${entry.course}</td></tr>`;
});
const tableHeadSection = `<table border='1'><tr><th>Name</th><th>Course</th></tr>`;
table = `${tableHeadSection}${table}</table>`;
document.querySelector("#display").innerHTML = table;
}
readTAsInfo();
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Displaying cats</title>
</head>
<body>
<h1>Cat Images</h1>
<label>Animation speed in milliseconds <input id="speed" type="text" value="1000"></label><br><br>
<input type="button" value="Start Displaying Cats" onclick="startAnimation()">
<input type="button" value="Stop Animation" onclick="stopAnimation()"><br><br>
<img id="downloadedImage" src="doesnotexistyet.png" height="300" alt="image"><br>
<div id="display"></div>
<script>
let animationId, animationStarted = false;
function downloadCatImage() {
let catImagesUrl = `https://api.thecatapi.com/v1/images/search`;
fetch(catImagesUrl)
.then(response => response.json())
.then(json => {
const imageUrl = json[0].url;
const img = document.querySelector("#downloadedImage");
img.src = imageUrl;
document.querySelector("#display").innerHTML = `Source: <a href="${imageUrl}">${imageUrl}</a>`;
});
}
function startAnimation() {
if (!animationStarted) { /* Preventing executing setInterval multiple times before stopping animation */
let intervalInMillisecs = document.querySelector("#speed").value;
animationId = setInterval(downloadCatImage, intervalInMillisecs);
animationStarted = true;
}
}
function stopAnimation() {
if (animationStarted) {
clearInterval(animationId);
animationStarted = false;
}
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fetching Image</title>
</head>
<body>
<h1>Fetching Random Cat Image</h1>
<input type="button" value="DownloadCatImage" onclick="downloadCatImage()"><br><br>
<img src="toPacifyHTMLValidator" id="downloadedImage" height="300" alt="catImg"><br>
<script>
function downloadCatImage() {
let catImageUrl = `https://api.thecatapi.com/v1/images/search`;
fetch(catImageUrl)
.then(response => response.json())
.then(json => {
console.log(json); /* Take a look at the console */
const imageUrl = json[0].url;
const img = document.querySelector("#downloadedImage");
img.src = imageUrl;
});
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script>
let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end
alert(`Retrieving data from ${url} (check console for results)`);
const promise = fetch(url);
console.log(promise);
promise.then(response => {console.log(response); return response.json()}).then(json => console.log(json)); // Process json object by displaying on the console
console.log("***** END OF SCRIPT *****"); // Check WHERE this message appears in the console
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script>
let url = "https://jsonplaceholder.typicode.com/todos/1"; // Notice the 1 at the end
alert(`Retrieving data from ${url}`);
fetch(url) // Get data
.then(response => response.text()) // Process response by retrieving text
.then(text => document.writeln(text)); // Displaying text
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script>
let url = "https://jsonplaceholder.typicode.com/todos/2";
alert(`Retrieving data from ${url} (check console for results)`);
fetch(url).then(response => response.json()).then(json => processObject(json));
function processObject({userId, id, title}) { // Notice destructoring
console.log("Data Retrieved\n");
console.log(`user Id: ${userId}`);
console.log(`id: ${id}`);
console.log(`title: ${title}`);
}
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8" />
</head>
<body>
<script>
let url = "https://jsonplaceholder.typicode.com/todos/1"; // Replace 1 with invalid value to see catch effect
alert(`Retrieving data from ${url} (check console for results)`);
fetch(url)
.then((response) => {
if (!response.ok) {
throw "Problem downloading";
} else {
return response.json();
}
})
.then((json) => processObject(json))
.catch((error) => console.log("Reporting error: " + error));
function processObject(json) {
console.log("Data Retrieved\n");
console.log(json);
console.log("Accessing properties\n");
console.log(`user Id: ${json.userId}`);
// throw "Faking an error took place"; // Uncomment to faking an error; will trigger catch above
console.log(`id: ${json.id}`);
console.log(`title: ${json.title}`);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example</title>
<meta charset="utf-8">
</head>
<body>
<script>
let url = "https://jsonplaceholder.typicode.com/todos/"; // Now retrieving a lot of entries
alert(`Retrieving data from ${url} (check console for results)`);
fetch(url)
.then(response => response.json())
.then(arrayOfObjects => printTitles(arrayOfObjects))
.catch(error => console.log("Reporting error: " + error));
function printTitles(arrayOfObjects) {
// Our response is an array of values
console.log("\n\n***** Titles Received *****\n");
for (let entry of arrayOfObjects) {
console.log(entry.title);
}
}
</script>
</body>
</html>
\ No newline at end of file
[
{"name": "Pete", "course": "CMSC335"},
{"name": "Rose", "course": "CMSC216"},
{"name": "Michael", "course": "CMSC335"},
{"name": "Laura", "course": "CMSC216"},
{"name": "Kathleen", "course": "CMSC335"}
]
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS JSON Example</title>
<style>
h2 {text-decoration: underline}
</style>
</head>
<body>
<script>
"use strict";
main();
function main() {
let obj = {
"name": "Mary",
"age": 45,
"salary": 20000.00,
"employed": true,
"boss": null,
"cars": ["toyota", "honda"], /* array example */
"friends": [{ /* array of objects */
"fname": "Peter"
}, {
"fname": "Rachel"
}]
};
document.writeln("<h2>JSON String (After stringify Object)</h2>");
let str = JSON.stringify(obj);
document.writeln(str);
document.writeln("<h2>After Parsing String</h2>")
let newObj = JSON.parse(str);
for (let prop in newObj) {
document.writeln(prop + "&rarr;" + newObj[prop] + "<br>");
}
document.writeln("<h2>Check console to see object corresponding to following string</h2>");
/* Using template literal */
let secondObjStr = `{
"school": "UMCP",
"zipCode": 20742
}`;
document.writeln("String: " + secondObjStr + "<br>");
let secondObj = JSON.parse(secondObjStr);
console.log(secondObj);
console.table(secondObj);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Objects Example</title>
</head>
<body>
<script>
main();
function main() {
/* Alternatives for creating an empty object */
let emptyObject1 = new Object();
let emptyObject2 = new Object(undefined);
let emptyObject3 = new Object(null);
let emptyObject4 = {};
/* Boolean Object alternative */
let booleanObject1 = new Object(true);
let booleanObject2 = new Boolean(true);
/* Number Object alternative */
let numObject1 = new Object(3);
let numObject2 = new Number(3);
/* String Object alternative */
let strObject1 = new Object("Hello world");
let strObject2 = new String("Hello world");
/* Using Object constructor for person object */
let person1 = new Object();
/* Adding properties */
/* Alternative to next assignment -> person1.name = "John"; */
person1["name"] = "John";
person1.age = 45;
person1.school = umcpSchool;
/* Printing person */
printPerson(person1);
/* Using object initializer/literal notation */
let person2 = {
name: "Mary", /* We could have used "name":"Mary" */
age: 30, /* We could have used "age": 30 */
school: umcpSchool, /* Assigning a method */
bestFriend: person1 /* Assigning an object */
};
/* Printing person */
printPerson(person2);
let exam = {
semester: "fall",
"difficulty-level": 10, /* Needs " " as key is not valid */
3: "midterm3",
"": "empty string"
};
exam[person1] = "person1";
/* Printing to console */
document.writeln("<br>***** Check console for output *****<br>");
console.log("\n\n ***** Printing exam object *****\n\n");
console.log(exam);
console.log("\n\n ***** Printing exam object using table *****\n\n");
console.table(exam); /* Using console.table */
console.log(" ***** Creating object copy *****\n");
let exam2 = Object.create(exam);
exam2['3'] = 'final';
console.table(exam2);
}
function printPerson(personParam) {
document.writeln("Name: " + personParam.name + ", ");
document.writeln("Age: " + personParam.age + ", ");
if (personParam.bestFriend != undefined) {
document.writeln(
"Best Friend: " + personParam.bestFriend.name + ", "
);
}
personParam.school();
}
function umcpSchool() {
document.writeln("University of MD College Park" + "<br>");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Example</title>
</head>
<body>
<script>
let option = prompt("Enter error, info, warn or log");
if (option === "error") {
console.error("Using console.error");
} else if (option === "info") {
console.info("Using console.info");
} else if (option === "warn") {
console.warn("Using console.warn");
} else if (option === "log") {
console.log("Using console.log");
} else {
console.log("Invalid option: " + option);
}
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>JS Example</title>
</head>
<body>
<script>
document.writeln(
"Before function declaration: " + product(3, 4) + "<br>"
);
/* Function declaration */
function product(x, y) {
return x * y;
}
document.writeln("Function declaration: " + product(3, 4) + "<br>");
/* Function expression (anonymous function) */
let productTwo = function (x, y) {
return x * y;
};
document.writeln("Function expression: " + productTwo(100, 200) + "<br>");
/* Using Function constructor */
let productThree = new Function("x", "y", "return x * y");
document.writeln("Function constructor: " + productThree(2, 3));
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Process Values</title>
</head>
<body>
<script>
"use strict";
main();
function main() {
let numberOfValues = Number(prompt("Enter number of values to print"));
/* We don't need to use window window.confirm */
let wantHTML = window.confirm(
"Press OK for formatted output and Cancel otherwise"
);
let printingFunction;
if (wantHTML) {
printingFunction = htmlFormatFunction;
} else {
printingFunction = textFormatFunction;
}
displayValues(numberOfValues, printingFunction);
}
function textFormatFunction(data) {
document.writeln(data);
}
function htmlFormatFunction(data) {
let output = "<span style='color:red;font-size:4em'><strong>";
output += data + " </strong></span>";
document.writeln(output);
}
function displayValues(maximum, printFunction) {
for (let curr = 1; curr < maximum; curr++) {
printFunction(curr);
}
printFunction(maximum);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Functions as Data</title>
</head>
<body>
<script>
"use strict";
/* We don't need to have a main function */
main();
function main() {
const sayHi = hello;
const hi = hello;
hi("John");
hello("John");
sayHi("John");
}
function hello(name) {
document.writeln("Hello " + name + "<br>");
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Program Template</title>
</head>
<body>
john
peter
<script>
"use strict";
console.log("window contents");
console.log(window);
console.log("globalThis contents");
console.log(globalThis);
let message;
if (window === globalThis) {
message = "the same";
} else {
message = "they are not the same";
}
document.writeln(message, "<br>");
let finalMessage = message + "<br>" + "Done";
alert(finalMessage);
var value = 10;
console.log("window.value is: " + window.value);
let secondValue = 10;
console.log("window.secondValue is: " + window.secondValue);
document.writeln("Output available in the console");
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Input/Output</title>
</head>
<body>
<script>
"use strict";
document.writeln("<strong>" + "Bill Calculation System</strong><br />");
let costPerCredit, numberOfCredits, tuitionCost;
/* Reading values from the user */
costPerCredit = Number(prompt("Enter cost per credit:"));
numberOfCredits = prompt("Enter number of credits:", 15);
/* Computing cost */
tuitionCost = costPerCredit * numberOfCredits;
document.writeln("<strong>Tuition Cost: </strong>" + tuitionCost);
</script>
</body>
</html>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment