Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript - Lecture 6 - Web Technologies (1019888BNR)

JavaScript - Lecture 6 - Web Technologies (1019888BNR)

This lecture forms part of the course Web Technologies given at the Vrije Universiteit Brussel.

Beat Signer

October 30, 2023
Tweet

More Decks by Beat Signer

Other Decks in Education

Transcript

  1. 2 December 2005 Web Technologies JavaScript Prof. Beat Signer Department

    of Computer Science Vrije Universiteit Brussel beatsigner.com
  2. Beat Signer - Department of Computer Science - [email protected] 2

    October 31, 2023 JavaScript ▪ High-level loosely typed dynamic language ▪ Introduced by Netscape in 1995 ▪ lightweight interpreted client-side programming ▪ Supports imperative, object-oriented and functional programming styles ▪ Nowadays also used in non-web-based apps ▪ Microsoft Office, PDF, … ▪ JavaScript implements the ECMAScript specification ▪ latest: ECMAScript 2023 [https://survey.stackoverflow.co/2023/] Most Popular Programming, Scripting, and Markup Languages
  3. Beat Signer - Department of Computer Science - [email protected] 3

    October 31, 2023 Adding JavaScript to a Webpage ▪ JavaScript code can be placed in the <head>, in the <body> or in external files <!DOCTYPE html> <html> <head> <tile>JavaScript Example</tile> ... <script> alert("Message in the header"); </script> <script src="example.js"></script> </head> <body> <h1>A First Example</h1> <script> document.write("<p>Text added by JavaScript</p>"); </script> <p id="p2">A second paragraph.</p> </body> </html>
  4. Beat Signer - Department of Computer Science - [email protected] 4

    October 31, 2023 Adding JavaScript to a Webpage … ▪ Advantages of external JavaScript files ▪ separation of HTML and code ▪ faster page load if JavaScript file is cached ▪ JavaScript code placed just before the </body> tag (end of the page) might improve page load ▪ display of HTML is not blocked by script loading ▪ alternatives (defer or async attributes) <script defer src="example1.js"></script> or <script async src="example2.js"></script> ▪ Use the latest version of the language by adding "use strict"; to the top of a script ▪ implicitly strict for code in a class body or a module
  5. Beat Signer - Department of Computer Science - [email protected] 5

    October 31, 2023 Execution of JavaScript Programs ▪ JavaScript program consists of all the code in or referenced from an HTML document ▪ bits of code share single global Window object providing access to the same underlying Document object (HTML document) ▪ JavaScript program is executed in two phases ▪ phase 1: document content is loaded (create DOM tree) and any code in <script> elements is executed ▪ phase 2: asynchronous and event-driven execution of code (event handlers installed during phase 1) ▪ JavaScript is single threaded - browser stops responding to input while scripts are executed ▪ JavaScript errors silently ignored by most browsers ▪ activate browser console for debugging (e.g. F12)
  6. Beat Signer - Department of Computer Science - [email protected] 6

    October 31, 2023 Browser Console ▪ Error 'aalert' shows up in the console
  7. Beat Signer - Department of Computer Science - [email protected] 7

    October 31, 2023 Output ▪ There are different possibilities for JavaScript output ▪ document.write() ▪ adds content to the page while loading ▪ deletes (overwrites) page if used after page has been loaded ▪ should only be used for testing (slow) ▪ console.log() ▪ outputs content to the browser console ▪ alert(), prompt() or confirm() ▪ outputs data in an alert, prompt or confirm message box ▪ innerHTML and outerHTML property ▪ adds content to an HTML element (via DOM tree) document.querySelector("p:nth-child(2)").innerHTML = "A new second paragraph.";
  8. Beat Signer - Department of Computer Science - [email protected] 8

    October 31, 2023 Variables and Data Types ▪ Variables have dynamic types ▪ Primitive data types ▪ string, number, bigint, boolean and symbol ▪ null and undefined ▪ Objects let x; // x has been declared but the value is 'undefined' x = "Albert Einstein"; // now x is a string x = 3.1415; // now x is a number typeof x; // number x = false; // now x is a boolean
  9. Beat Signer - Department of Computer Science - [email protected] 9

    October 31, 2023 Strings ▪ Any text between single (') or double quotes (") ▪ Strings are immutable ▪ Special characters (e.g. '\', '\t' or '\n') have to be escaped with a backslash (\) let hello = "Hello World"; let correct = "This is \"correct\""; // escaped double quotes let tmp = hello.length; // 11 tmp = hello + ". " + correct; // Hello World. This is "correct" tmp = hello.charAt(1); // e tmp = hello.toUpperCase(); // HELLO WORLD tmp = hello.replace("World", "VUB"); // replace first occurence of 'World' with 'VUB'
  10. Beat Signer - Department of Computer Science - [email protected] 10

    October 31, 2023 Numbers ▪ 64-bit floating point numbers (IEEE 754 standard) ▪ mantissa (52 bits), exponent (11 bits) and sign (1 bit) ▪ NaN indicates that a value is not a number ▪ Infinity for values that are too large to be represented let x = 42.00; let y = 42; let z = 42e3; // 42000 let x = 42 / "foo"; // but what about 'x = 42 + "foo"? isNaN(x); // returns true // what is the difference between '10 + 10 + "foo"' and '"foo" + 10 + 10'? let x = 42 / 0; // x becomes Infinity
  11. Beat Signer - Department of Computer Science - [email protected] 11

    October 31, 2023 Numbers … ▪ Rounding errors ▪ due to rounding errors we might not always get the expected result let x = 0.3 + 0.6; // 0.8999999999999999 let x = (0.3 * 10 + 0.6 * 10) / 10; // possible solution (resulting in 0.9)
  12. Beat Signer - Department of Computer Science - [email protected] 12

    October 31, 2023 BigInt ▪ Represent whole numbers larger than 253-1 (or Number.MAX_SAFE_INTEGER) ▪ introduced for compatibility with 64-bit integer representation in many other programming languages and APIs ▪ BigInt values can be of arbitrary size (not limited to 64-bit) ▪ Cannot mix Number and BigInt operands in mathematical expressions let x = 2000n; // BigInt literals are a string of digits followed by 'n' let s = "1" + "0".repeat(100) ; // one googol let result = x + BigInt(s);
  13. Beat Signer - Department of Computer Science - [email protected] 13

    October 31, 2023 Boolean ▪ Booleans can have the values true or false let x = true; let y = false; let z = 5 > 3; // true
  14. Beat Signer - Department of Computer Science - [email protected] 14

    October 31, 2023 Date and Math Objects ▪ Date object can be used to work with dates ▪ Math object can be used for various mathematical operations and offers some constants (e.g. PI and E) ▪ Note: BigInt values cannot be used with Math methods const now = new Date(); const nextWeek = new Date("2023-11-07T13:00:00"); // ISO 8610 syntax let milis = now.getTime(); // time in milliseconds since January 1, 1970 let test = nextWeek.getTime() > milis; // true Math.random(); // random number between 0 (inclusive) and 1 (exclusive) Math.round(3.6); // 4 (rounded to the nearest integer) Math.max(4,10,3); // 10 (number with the highest value)
  15. Beat Signer - Department of Computer Science - [email protected] 15

    October 31, 2023 Objects ▪ Container of properties (name / value) where a value can be any JavaScript value (including other objects) ▪ Two possibilities to retrieve object values ▪ second option only works for legal JavaScript names and non-reserved words const student = { firstName: "John", lastName: "Harper", height: 182 }; student["firstName"]; student.lastName;
  16. Beat Signer - Department of Computer Science - [email protected] 16

    October 31, 2023 Objects ... ▪ Existing values can be updated, new properties can be added and existing properties can be deleted ▪ Objects are passed by reference and not by value student.lastName = "Wayne"; student.address = { street: "Pleinlaan", number: 2 }; delete student.lastName; let x = student; // student object created before x.firstName = "Peter"; let name = student.firstName; // name is "Peter" since x and student are references to the same object
  17. Beat Signer - Department of Computer Science - [email protected] 17

    October 31, 2023 Objects … ▪ Cloning of objects (deep copy) is not trivial in JavaScript ▪ Object.assign(target, source) only does a shallow copy ▪ use libraries (e.g. Lodash) for a clone() method
  18. Beat Signer - Department of Computer Science - [email protected] 18

    October 31, 2023 Arrays ▪ An array is a variable that can hold multiple values which can be accessed via an integer offset ▪ values of different types might be mixed ▪ Other methods to sort arrays, combine arrays etc. const points = [10, 5, 17, 42]; points.length; // number of elements (4) points[1]; // accesses the element with the given offset (5) points[points.length] = 13; // adds 13 to the end of the array [10, 5, 17, 42, 13] let last = points.pop(); // removes the last element [10, 5 , 17 , 42] let l = points.push(2); // adds 2 at the end and returns the length (5) let first = points.shift(); // removes the first element [5, 17, 42, 2] l = points.unshift(7); // adds 7 to the beginning and returns the length (5) delete points[2]; // the third element will be undefined const matrix = [[3, 1, 2], [9, 6, 4], [5, 7, 8]]; // array of arrays ("2D" array) matrix [1][2]; // 4
  19. Beat Signer - Department of Computer Science - [email protected] 19

    October 31, 2023 Functions ▪ A function is a block of code to perform a particular task ▪ enables the reuse of code ▪ functions are objects and can be used like any other value - can be stored in variables, objects and arrays - can be passed as argument to functions or returned from functions ▪ access to a function without the () operator returns the definition of a function ▪ Shorthand arrow function syntax ▪ e.g. to pass anonymous function as argument of other function function multiply(p1, p2) { return p1 * p2; } let r = multiply(3, 4); // 12 (a, b) => a * b + 100;
  20. Beat Signer - Department of Computer Science - [email protected] 20

    October 31, 2023 Scope ▪ Local variables declared within a function have block-level scoping ▪ A variable declared outside of a function has global scope ▪ Local variables deleted when the block is completed ▪ Function arguments (parameters) work as local variables within functions ▪ Warning ▪ old var syntax does not offer block-level scoping but rather provides function scoping
  21. Beat Signer - Department of Computer Science - [email protected] 21

    October 31, 2023 Objects Revisited ▪ Functions can be added to objects (methods) ▪ Multiple objects can be created via an object constructor function (prototype) // Let us assume that we have the student object that was created earlier student.fullName = function() { return this.firstName + " " + this.lastName; } function Student(firstName, lastName, height) = { this.firstName = firstName; this.lastName = lastName; this.height = height; this.fullName = function() {return this.firstName + " " + this.lastName;} }; const student1 = new Student("Audrey", "Sanctorum", 174); const student2 = new Student("Maxim", "Van de Wynckel", 177);
  22. Beat Signer - Department of Computer Science - [email protected] 22

    October 31, 2023 Classes ▪ Classes have been introduced in ECMAScript 2015 ▪ simplifies inheritance etc. class Person { constructor(firstName, lastName, height) { this.firstName = firstName; this.lastName = lastName; this.height = height; } fullName() { return this.firstName + " " + this.lastName; } } class Student extends Person { constructor(firstName, lastName, height, studentID) { super(firstName, lastName, height); this.studentID = studentID; } }
  23. Beat Signer - Department of Computer Science - [email protected] 23

    October 31, 2023 Classes … const student = new Student("Audrey", "Sanctorum", 174, 93283982); console.log(student.fullname()); // Audrey Sanctorum console.log(student instanceof Person); // true console.log(student instanceof Student); // true
  24. Beat Signer - Department of Computer Science - [email protected] 24

    October 31, 2023 Modules ▪ Modules can be used to control the scoping instead of using a shared-everything approach ▪ each file is a module ▪ export keyword to expose code to other modules ▪ exported functionality can be accessed from another module via the import keyword export let counter = 0; export function multiply(p1, p2) { return p1 * p2; } ... import multiply from "./example.js"; ... example.js main.js
  25. Beat Signer - Department of Computer Science - [email protected] 25

    October 31, 2023 Modules … ▪ can use single export statement at the end of a module ▪ tell the browser that we want to use modules ▪ code in modules is automatically in strict mode ▪ other imported modules will be automatically downloaded let counter = 0; function multiply(p1, p2) { return p1 * p2; } ... export {multiply, counter}; <script type="module" src="main.js"></script> example.js
  26. Beat Signer - Department of Computer Science - [email protected] 26

    October 31, 2023 Conditional Statement ▪ Used to perform different actions based on different conditions let mention = ""; if (grade < 10) { mention = "Fail"; } else if (grade < 13.6) { mention = "Pass"; } else if (grade < 15.4) { mention = "Distinction"; } else if (grade < 17) { mention = "Great Distinction"; } else { mention = "Greatest Distinction"; }
  27. Beat Signer - Department of Computer Science - [email protected] 27

    October 31, 2023 Loops ▪ For Loop ▪ For / In Loop ▪ iterate over object properties ▪ While Loop for (let i = 0; i < 10; i++) { text += "Number: " + i + "<br />"; } for (x in student) { text += " " + student[x]; // Add all properties of 'student' to text string } while (i < 10) { text += "Number: " + i + "<br />"; i++; }
  28. Beat Signer - Department of Computer Science - [email protected] 28

    October 31, 2023 JavaScript Best Practices ▪ Avoid (minimise) global variables ▪ global variables can lead to name collisions for sub-programs but modules can be used to fix the problem ▪ Always initialise variables when they are declared ▪ avoids undefined values ▪ use strict mode to avoid undeclared variables ▪ Declare objects and arrays with const ▪ prevents accidental change of type ▪ Always use the === and !== equality operators ▪ == and != do some automatic type coercion (with complicated rules) if the types are not equal
  29. Beat Signer - Department of Computer Science - [email protected] 29

    October 31, 2023 JavaScript Best Practices ... ▪ Avoid block-less if, while, do or for statements ▪ Avoid the use of eval() ▪ runs text as code and leads to performance and security issues if (x > 10) { t = true; }
  30. Beat Signer - Department of Computer Science - [email protected] 30

    October 31, 2023 DOM Revisited News html head body document title Vrije Univer ... h1 p p … … a Internationa ... Vrije Uni ... href https:// ... document node element node attribute node text node root node
  31. Beat Signer - Department of Computer Science - [email protected] 31

    October 31, 2023 JavaScript DOM Manipulation document.getElementById("id5"); document.getElementsByTagName("p"); document.getElementsByClassName("highlight"); document.querySelector("#id5"); // newer CSS selector document.querySelector("#id5").innerHTML = "Let's <b>change</b> the text"; document.querySelector("#id5").textContent = "Let's change the plain text"; document.querySelectorAll("p.highlight"); // all <p> elements of class 'highlight' document.querySelectorAll("h1, h2, h3"); // all <h1>, <h2> and <h3> elements // Elements have properties for their attributes let image = document.querySelector("#i42"); let url = image.src; image.alt = "new alt text"; // Class attribute (for CSS style sheets) might be updated let image = document.querySelector("#i42"); image.classList.remove("hidden"); image.classList.add("animated"); let classesName = image.className; // returns class names as string // Create new elements let paragraph = document.createElement("p"); paragraph.append("Hello World"); document.querySelector("#id5").after(paragraph)
  32. Beat Signer - Department of Computer Science - [email protected] 32

    October 31, 2023 DOM Navigation ▪ A set of properties defined on all nodes allow to navigate the DOM tree (including elements, text, comments, …) ▪ parentNode, childNodes, firstChild, lastChild, nextSibling, previousSibling, nodeType, nodeName, … ▪ Another set of properties defined on element nodes only allows to navigate the DOM tree (only element nodes) ▪ parentNode, children, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling, …
  33. Beat Signer - Department of Computer Science - [email protected] 33

    October 31, 2023 Event Categories ▪ Can add JavaScript handlers for various event types ▪ device-dependent input events - mousedown, mousemove, mouseover, mouseup, keydown, keyup, … ▪ device-independent input events - click, input, pointerdown, pointermove, pointerup, … ▪ user interface events - focus, change, submit, … ▪ state-change events - load, DOMContentLoaded, online, offline, … ▪ API-specific events - waiting, playing, seeking, …
  34. Beat Signer - Department of Computer Science - [email protected] 34

    October 31, 2023 Registering Event Handlers ▪ We can directly register handlers on the HTML elements ▪ We can also register event handlers via properties or the addEventListener() method defined on elements <button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button> <button onclick="this.innerHTML = Date()">The time is?</button> <button onclick="displayDate()">The time is?</button> let b = documemt.querySelector("#mybutton"); b.onclick = function() {console.log("Thanks for clicking!"); }; b.addEventListener("click", () => {console.log("Thanks again!"); }); b.addEventListener("click", handleClick);
  35. Beat Signer - Department of Computer Science - [email protected] 35

    October 31, 2023 JavaScript Object Notation (JSON) ▪ Developed as an XML alternative to represent JavaScript objects as strings (language independent) ▪ Easy to produce and faster to parse than XML ▪ supports different data types ▪ JSON is based on a subset of JavaScript ▪ JSON document can be read via the JavaScript eval() function - security issues: note that this approach can be dangerous if the source is not trusted since any JavaScript code might be executed ▪ recent browsers offer a JSON parser (JSON.parse()) - recognises only JSON data types and rejects any scripts ▪ Many Web 2.0 Applications offer a JSON interface ▪ Flickr, YouTube, Delicious, ...
  36. Beat Signer - Department of Computer Science - [email protected] 36

    October 31, 2023 JSON Data Types ▪ The values themselves can be simple values (number, boolean or string), arrays or objects ▪ nesting is supported ▪ BigInt values not supported by default Type Description Number integer, real or float Boolean true or false String double-quoted Unicode (use backslash for escaping) Array comma-separated ordered sequence of values enclosed in square brackets Object comma-separated collection of key:value pairs enclosed in curly brackets null null value
  37. Beat Signer - Department of Computer Science - [email protected] 37

    October 31, 2023 JSON Syntax Diagrams http://www.json.org
  38. Beat Signer - Department of Computer Science - [email protected] 38

    October 31, 2023 JSON Example { "surname": "Signer", "forename": "Beat", "address": { "street": "Pleinlaan 2", "city": "Brussels", "postalCode": 1050, "country": "Belgium" }, "phoneNumbers": [ { "type": "office", "number": "123 456 789" }, { "type": "fax", "number": "987 654 321" } ] }
  39. Beat Signer - Department of Computer Science - [email protected] 39

    October 31, 2023 JavaScript Libraries ▪ Modernizr.js ▪ check availability of certain HTML, CSS and JavaScript features in a browser ▪ D3.js ▪ interactive data visualisations (Data-Driven Documents) ▪ Leaflet ▪ interactive maps ▪ …
  40. Beat Signer - Department of Computer Science - [email protected] 40

    October 31, 2023 Exercise 6 ▪ JavaScript and HTML5 APIs
  41. Beat Signer - Department of Computer Science - [email protected] 41

    October 31, 2023 References ▪ JavaScript: The Definitive Guide: Master the World's Most-used Programming Language, David Flanagan, O'Reilly (7th edition), May 2020, ISBN-13: 978-1491952023 ▪ Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers, Nicholas C. Zakas, No Starch Press (1st edition), October 2016 ISBN-13: 978-1593277574 Programming TypeScript: Making Your JavaScript Applications Scale, Boris Cherny, O'Reilly (1st edition), May 2019 ISBN-13: 978-1492037651
  42. Beat Signer - Department of Computer Science - [email protected] 42

    October 31, 2023 References ... ▪ W3Schools JavaScript Tutorial ▪ https://www.w3schools.com/js/ ▪ JavaScript Tutorial ▪ https://javascript.info/ ▪ Mozilla Developer Network (MDN) JavaScript Tutorial ▪ https://developer.mozilla.org/en-US/docs/Web/JavaScript ▪ JSLint: The JavaScript Code Quality Tool ▪ https://www.jslint.com