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

JavaScript - Lecture 6 - Web Technologies (1019...

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest. →
Avatar for Beat Signer Beat Signer PRO
October 27, 2026

JavaScript - Lecture 6 - Web Technologies (1019888BNR)

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

Avatar for Beat Signer

Beat Signer PRO

October 27, 2026

More Decks by Beat Signer

Other Decks in Education

Transcript

  1. Web Technologies JavaScript Prof. Beat Signer Department Vrije beatsigner.com Universiteit

    of Computer Brussel Science Department of Computer Science Vrije Universiteit Brussel beatsigner.com 2 December 2005
  2. 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 ▪ Most Popular Programming, Scripting and Markup Languages Microsoft Office, PDF, … ▪ JavaScript implements the ECMAScript specification ▪ October 27, 2026 latest: ECMAScript 2026 (or ES17) [https://survey.stackoverflow.co/2026/] Beat Signer - Department of Computer Science - [email protected] 2
  3. Adding JavaScript to a Webpage <!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> ▪ JavaScript code can be placed in the <head>, in the <body> or in external files October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 3
  4. 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 implicit strict for code in a class body or a module ▪ implicit activation when new features are used ▪ October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 4
  5. 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 ▪ October 27, 2026 activate browser console for debugging (e.g. F12) Beat Signer - Department of Computer Science - [email protected] 5
  6. Browser Console ▪ Error 'aalert' shows up in the console

    October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 6
  7. 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."; October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 7
  8. Variables and Data Types ▪ Variables have dynamic types 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 ▪ Primitive data types string, number, bigint, boolean and symbol ▪ null and undefined ▪ ▪ Objects October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 8
  9. 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' October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 9
  10. Numbers ▪ 64-bit floating point numbers (IEEE 754 standard) ▪

    mantissa (52 bits), exponent (11 bits) and sign (1 bit) let x = 42.00; let y = 42; let z = 42e3; // 42000 ▪ NaN indicates that a value is not a number 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'? ▪ Infinity for values that are too large to be represented let x = 42 / 0; // x becomes Infinity October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 10
  11. 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) October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 11
  12. 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) ▪ 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); ▪ Cannot mix Number and BigInt operands in mathematical expressions October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 12
  13. Boolean ▪ Booleans can have the values true or false

    let x = true; let y = false; let z = 5 > 3; // true October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 13
  14. Date and Math Objects ▪ Date object can be used

    to work with dates const now = new Date(); const nextWeek = new Date("2026-11-03T13:00:00"); // ISO 8610 syntax let milis = now.getTime(); // time in milliseconds since January 1, 1970 let test = nextWeek.getTime() > milis; // true ▪ Math object can be used for various mathematical operations and offers some constants (e.g. PI and E) 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) ▪ Note: BigInt values cannot be used with Math methods October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 14
  15. Objects ▪ Container of properties (name/value) where a value can

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

    can be added and existing properties can be deleted student.lastName = "Wayne"; student.address = { street: "Pleinlaan", number: 2 }; delete student.lastName; ▪ Objects are passed by reference and not by value 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 October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 16
  17. 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 ▪ October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 17
  18. 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 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 ▪ Other methods to sort arrays, combine arrays etc. October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 18
  19. 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 an argument to functions or returned from functions ▪ access to a function without the () operator returns the definition of a function function multiply(p1, p2) { return p1 * p2; } let r = multiply(3, 4); // 12 ▪ Shorthand arrow function syntax ▪ e.g. to pass anonymous function as argument of another function (a, b) => a * b + 100; October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 19
  20. 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 ▪ October 27, 2026 old var syntax does not offer block-level scoping but rather provides function scoping Beat Signer - Department of Computer Science - [email protected] 20
  21. Objects Revisited ▪ Functions can be added to objects (methods)

    // Let us assume that we have the student object that was created earlier student.fullName = function() { return this.firstName + " " + this.lastName; } ▪ Multiple objects can be created via an object constructor function (prototype) 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); October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 21
  22. Classes ▪ Classes have been introduced in ECMAScript 2015 (6)

    ▪ 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; } } October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 22
  23. 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 October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 23
  24. 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 ▪ example.js export let counter = 0; export function multiply(p1, p2) { return p1 * p2; } ... main.js import multiply from "./example.js"; ... October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 24
  25. Modules … ▪ can use single export statement at the

    end of a module example.js let counter = 0; function multiply(p1, p2) { return p1 * p2; } ... export {multiply, counter}; ▪ tell the browser that we want to use modules code in modules is automatically in strict mode ▪ other imported modules will be automatically downloaded ▪ <script type="module" src="main.js"></script> October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 25
  26. 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"; } October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 26
  27. Loops ▪ For Loop for (let i = 0; i

    < 10; i++) { text += "Number: " + i + "<br />"; } ▪ For/In Loop ▪ iterate over object properties for (x in student) { text += " " + student[x]; // Add all properties of 'student' to text string } ▪ While Loop while (i < 10) { text += "Number: " + i + "<br />"; i++; } October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 27
  28. 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 October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 28
  29. JavaScript Best Practices ... ▪ Avoid block-less if, while, do

    or for statements if (x > 10) { t = true; } ▪ Avoid the use of eval() ▪ October 27, 2026 runs text as code and leads to performance and security issues Beat Signer - Department of Computer Science - [email protected] 29
  30. DOM Revisited document html root node head body title h1

    Vrije Univer ... News document node Internationa ... p … p … a href Vrije Uni ... https:// ... element node attribute node text node October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 30
  31. 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) October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 31
  32. 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) ▪ October 27, 2026 parentNode, children, firstElementChild, lastElementChild, nextElementSibling, previousElementSibling, … Beat Signer - Department of Computer Science - [email protected] 32
  33. 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, … October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 33
  34. Registering Event Handlers ▪ We can directly register handlers on

    the HTML 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> ▪ We can also register event handlers via properties or the addEventListener() method defined on elements let b = documemt.querySelector("#mybutton"); b.onclick = function() {console.log("Thanks for clicking!"); }; b.addEventListener("click", () => {console.log("Thanks again!"); }); b.addEventListener("click", handleClick); October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 34
  35. 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 ▪ October 27, 2026 Flickr, YouTube, Delicious, ... Beat Signer - Department of Computer Science - [email protected] 35
  36. JSON Data Types 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 ▪ The values themselves can be simple values (number, boolean or string), arrays or objects nesting is supported ▪ BigInt values not supported by default ▪ October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 36
  37. 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" } ] } October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 38
  38. 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 ▪ … October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 39
  39. Exercise 6 ▪ JavaScript and HTML5 APIs October 27, 2026

    Beat Signer - Department of Computer Science - [email protected] 40
  40. 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 October 27, 2026 Beat Signer - Department of Computer Science - [email protected] 41
  41. 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 ▪ October 27, 2026 https://www.jslint.com Beat Signer - Department of Computer Science - [email protected] 42