Slides JavaScript Essentials
Slides JavaScript Essentials
JavaScript Essentials
1-3 March 2021
1
Some questions to you
before we dive in!
2 . 1
Number of programs written?
(all by yourself)
2 . 2
Favourite programming
language?
2 . 3
Parts of JavaScript you know?
(you can give more than one answer)
2 . 4
Parts of JavaScript you wish
you knew better?
(max 3 answers)
2 . 5
What is JavaScript?
3 . 1
JavaScript is
a dynamically typed, interpreted, scripting language
3 . 2
JavaScript lets you
script event driven user interactions inside the browser
3 . 3
JavaScript has
Java-like syntax, garbage collection,
prototypal inheritance, rst-class functions
3 . 4
History of JavaScript
4 . 1
1995
Brendan Eich invents JavaScript at Netscape
In just 10 days!
4 . 2
1996
Netscape 2.0 embeds the SpiderMonkey engine
JScript powers Internet Explorer 3
The First Browser War has begun
4 . 3
1997
First version of ECMAScript (ECMA-262 standard)
4 . 4
1998
ECMAScript 2 is also standardized as ISO/IEC 16262
4 . 5
1999
ES3 is standardized based on Netscape 4 features
4 . 6
2000
Netscape 6 succumbs to Internet Explorer 5
AJAX takes o thanks to IE5's XMLHTTP ActiveX control
The First Browser War is over
4 . 7
2001
4 . 8
2002
4 . 9
2003
4 . 10
2004
Work on ES4 standardization begins
Firefox is born from open-sourced Netscape code
Mozilla and Opera found the WHATWG
The Second Browser War begins
4 . 11
2005
4 . 12
2006
4 . 13
2007
ES4 standardization fails because of internal dissent
Standardization of ES3.1 begins in parallel
4 . 14
2008
TC39 is founded to work on ES3.1
ES4 features are reworked into ECMAScript Harmony
ES4 is de nitely abandoned
Google releases the rst version of Chrome
4 . 15
2009
ECMAScript 3.1 is standardized as ECMAScript 5
4 . 16
2010
4 . 17
2011
4 . 18
2012
4 . 19
2013
4 . 20
2014
4 . 21
2015
ES6 Harmony is standardized as ECMAScript 2015
4 . 22
2016
ECMAScript 2016 is standardized
4 . 23
2017
ECMAScript 2017 is standardized
Google Chrome owns over 60% browser market share
The Second Browser War is over
4 . 24
2018
ECMAScript 2018 is standardized
4 . 25
2019
ECMAScript 2019 is standardized
4 . 26
2020
ECMAScript 2020 is standardized
4 . 27
You get it...
4 . 28
What does JavaScript
look like?
5 . 1
Question:
What does JavaScript have in
common with Java?
5 . 2
JavaScript is vaguely Java-like
JavaScript
for (var i = 0; i < 10; i++) {
console.log("number " + i);
}
Java
for (int i = 0; i < 10; i++) {
System.out.println("number " + i);
}
5 . 3
It's got names
5 . 4
It's got names
5 . 5
It's got names
5 . 6
It's got keywords
5 . 7
It's got literals
5 . 8
It's got punctuation
Lots of it!
5 . 9
Curly braces...
for (var i = 0; i < 10; i++) {
console.log("number " + i);
}
5 . 10
... and semicolons
for (var i = 0; i < 10; i++) {
console.log("number " + i)
}
5 . 11
It's got comments, too
5 . 12
What about whitespace?
Whitespace between names is mandatory
var x = 10;
var y = 20;
var
z = 30;
vark = 40;
for(var i=0;i<10;i++){console.log(i*2);}
5 . 13
Strict mode
A JavaScript variant
"use strict"
6
Example:
Hello, World!
writing the code
running
debugging
7 . 1
Question:
Is HTML a programming
language?
7 . 2
How does JavaScript
work?
8 . 1
Execution model
Scripts are lists of statements
Statements are composed of
syntactical constructs
expressions
Expressions are evaluated to produce
values
side e ects
Expressions are composed of
operators
more values or expressions
8 . 2
A simple example
console.log(5 * 10);
8 . 3
A simple example
console.log(5 * 10);
A statement...
8 . 4
A simple example
console.log(5 * 10);
8 . 5
A simple example
console.log(5 * 10);
An expression
8 . 6
A simple example
console.log(5 * 10);
8 . 7
A simple example
console.log(5 * 10);
8 . 8
A simple example
console.log( 50 );
8 . 9
A simple example
console.log( 50 );
8 . 10
A simple example
undefined; // prints: 50
8 . 11
Values
Values are carried by
Literals
Names
Expressions
Names with associated values are called variables
8 . 12
Types
Values can be of di erent types:
Primitive Reference
Null Object
Unde ned Function
Boolean
Number
String
Symbol ES2015
BigIntES2020
8 . 13
Type coercion
Expressions can mix values of di erent types
Values are automatically converted to a valid type
Automatic conversions are called type coercions
"HAL " + 9000; // "HAL 9000"
"9" * [5]; // 45
8 . 14
Type coercion
Expressions can mix values of di erent types
Values are automatically converted to a valid type
Automatic conversions are called type coercions
"HAL " + 9000; // "HAL 9000"
"9" * [5]; // 45
8 . 15
Operators
Arithmetic Increment Bitwise
+ ++ &
- -- |
* ^
/ ~
% >>
** ES2016
>>>
<<
8 . 16
Operators
Equality Relational Logical
== < !
!= <= &&
=== > ||
!== >= ?? ES2020
in
instanceof
8 . 17
Truthiness
In JavaScript, some values are considered falsey
undefined == false;
null == false;
"" == false;
0 == false;
8 . 18
Sometimes it gets very confusing...
"" == 0; // falsey
"0" == 0; // type coercion
8 . 19
Operators
Assignment
= &= &&= ES2021
+= |= ||= ES2021
-= ^= ??= ES2021
*= >>=
/= >>>=
%= <<=
**= ES2016
8 . 20
Operators
Dereference Conditional Special
[ ] ? : ,
. new
?. ES2020 delete
void
typeof
await ES2017
8 . 21
Statements
9 . 1
Variable declaration
var x = 10;
var y;
var z = 4, w = 12;
9 . 2
Code blocks
Group statements together
Seldom used alone
Often used as part of other statements
No trailing semicolon needed
{
// statements...
}
9 . 3
Block scoped variables ES2015
const x = 3;
// x = 6; // TypeError: invalid assignment to const 'x'
let y = 4, z = 5;
{
let x = 7;
y = 8;
console.log(x, y, z); // prints: 7 8 5
}
console.log(x, y, z); // prints: 3 8 5
9 . 5
Function declaration
function sum(a, b) {
return a + b;
}
function logInfo(message) {
console.log("INFO", message);
}
9 . 6
if / else
if (z > x) {
console.log("Big z");
}
if (x > 20) {
console.log("Very big x");
} else if (x > 10) {
console.log("Big x");
} else {
console.log("Small x");
}
9 . 7
switch / case
switch (name) {
case "Jim":
case "Joe":
console.log("Hey, man!");
break;
case "Jane":
case "Jill":
console.log("Good morning, Madam");
break;
default:
console.log("Hello dear guest");
}
9 . 8
Loops: while and do / while
while (x > 0) {
console.log("until x becomes zero", x--);
}
do {
console.log("at least once")
} while (false);
9 . 9
Loops: for
for (var i = 0; i < 10; i++) {
console.log("number", i);
}
9 . 10
Breaking statements
continue = leave current loop iteration
break = leave current loop
return = leave current function
throw = crash the script
9 . 11
Labeled statements
mainLoop: for (var i = 0; i < 100; i++) {
for (var j = 0; j < 100; j++) {
if (i * j > 1000) {
break mainLoop;
}
}
}
9 . 12
Error handling
Some operations may throw errors
const nobody = null;
nobody.name; // TypeError: nobody is null
9 . 13
Errors can be recovered by catching them
try {
const nobody = null;
nobody.name;
} catch (e) {
console.error(e.message); // prints: nobody is null
}
9 . 14
Data structures
One name -> multiple values
10 . 1
Objects
Take up some space in memory
Aggregate several properties
Each property is like an embedded variable
a key with an assigned value
Objects can be referenced by variables
10 . 2
Object literals
const jerry = {
name: "Jerry", // "name" = key, "Jerry" = value
age: 33,
skills: { // Nested object value
JavaScript: 5,
HTML: 3,
CSS: 3,
"Node.js": 2, // Key is not a valid name (contains .)
},
};
10 . 3
Property access
jerry.name; // "Jerry"
jerry["age"]; // 33
jerry.skills.JavaScript; // 5
const k = "JavaScript";
jerry.skills[k]; // 5
jerry.team; // undefined
10 . 4
jerry.age += 1; // set property 'age'
jerry.age; // 34
10 . 5
Null pointer dereferencing
let jimmy;
console.log(jimmy.name); // TypeError: jimmy is undefined
console.log(jimmy && jimmy.name); // would print: undefined
10 . 6
Optional chaining operator ES2020
let jimmy;
console.log(jimmy?.name); // prints: undefined
10 . 7
Object references
Objects are referenced by variables
const me = jerry;
me.age = 35;
jerry.age; // 35
10 . 8
Loops: for / in
Loop over an object's keys
for (let k in jerry) {
console.log(k, jerry[k]);
}
10 . 9
Arrays
A kind of object holding an indexed sequence of values
10 . 10
Array literals
const numbers = [1, 2, 3, 4, 5, 6, 7];
const fruit = ["Apple", "Orange", "Peach", "Mango"];
const people = [
{ name: "John", job: "singer" },
{ name: "Paul", job: "guitarist" },
{ name: "George", job: "guitarist" },
{ name: "Ringo", job: "drummer" },
];
10 . 11
Element access
fruit[0]; // Apple
fruit[1]; // Orange
fruit[2]; // Peach
fruit[3]; // Mango
fruit.length; // 4
fruit[4]; // undefined
fruit.xyzzy; // undefined;
10 . 12
fruit[0] = "Kiwi"; // replace element
fruit; // [Kiwi, Orange, Peach, Mango]
fruit[7] = "Pineapple";
fruit; // [Kiwi, Orange, Peach, Mango, Coconut, , , Pineapple]
fruit.length; // 8
10 . 13
Array length
The length property always tracks the actual length
It can be read and written as well
10 . 14
Destructuring ES2015
10 . 15
Iterable destructuring
10 . 16
Object destructuring
const jerry = {
name: "Jerry",
age: 33,
interests: ["Surf", "Kendo", "Pizza"],
};
10 . 17
const { interests: [fun, moreFun, best] } = jerry;
fun; // Surf
moreFun; // Kendo
best; // Pizza
10 . 18
const people = [
{ name: "John", jobs: ["singer", "songwriter"] },
{ name: "Paul", jobs: ["bass player", "guitarist"] },
{ name: "George", jobs: ["guitarist"] },
{ name: "Ringo", jobs: ["drummer"] },
];
name; // John
job1; // guitarist
job2; // drummer
10 . 19
Spread syntax ES2015
10 . 20
Object spread ES2018
10 . 21
Question:
Why do we need
data structures?
11
Functions
Are executable objects made of reusable instructions
12 . 1
Declaration
function hello() { // function name
// function body
console.log("Hello, World!");
}
12 . 2
Invocation
12 . 3
Parameters
function sayHello(from, to) {
console.log(from, "says hello to", to);
}
12 . 4
sayHello("Joe", "Jody"); // prints: Joe says hello to Jody
invocation
12 . 5
Default parameters ES2015
12 . 6
Rest parameters ES2015
12 . 7
Spread arguments ES2015
12 . 8
Return value
function constant42() {
return 42;
}
const theAnswer = constant42(); // 42
function sum(a, b) {
return a + b;
}
const total = sum(1, sum(2, 3)); // 6
12 . 9
Invocation is a kind of expression
function helloTo(who) {
who = who || "World";
return "Hello, " + who + "!";
}
12 . 10
Default return value is undefined
function printHelloTo(who) {
console.log(helloTo(who));
}
12 . 11
Functions are values, too
typeof hello === "function";
12 . 12
Higher order functions
function doTwice(action) {
action();
action();
}
function printMessage() {
console.log("Jeez, Louise");
};
doTwice(printMessage); // prints message twice
12 . 13
Higher order functions
function makeDoTwice(action) {
return function() {
action();
action();
};
}
const twiceTheMessage = makeDoTwice(printMessage);
twiceTheMessage(); // prints message twice
12 . 14
Function literals
(a.k.a. anonymous functions, function expressions,
lambda expressions)
const multiply = function(a, b) {
return a * b;
};
12 . 15
... like some functional programming idioms
function filter(array, predicate) {
const result = [];
for (let i = 0; i < array.length; i++) {
if (predicate(array[i]))
result[result.length] = array[i];
}
return result;
}
12 . 16
Arrow functions ES2015
12 . 17
... makes using functional idioms more readable.
// regular function syntax
filter([1, 2, 3, 4, 5], function(x) { return x < 3 });
12 . 18
Methods
const actor = {
act: function() {
console.log("To be or not to be?");
},
};
12 . 19
JavaScript APIs
Interfaces to functionality available to JavaScript code
13 . 1
ECMAScript Core API
General purpose functionality
Embedded in every ECMAScript implementation
String manipulation, arrays, collections, dates,
regular expressions, objects, functions, ...
13 . 2
Web APIs
Client-side, browser-speci c functionality
De ned by the HTML 5 standard
DOM, AJAX, Web Storage, Web Workers, Canvas, ...
13 . 3
Node.js APIs
Server-side functionality
De ned by the Node.js speci cation
File system, IO streams, networking, OS, processes ...
13 . 4
Third-party APIs
Libraries
Frameworks
Interfaces to external services
13 . 5
ECMAScript Core API
Utility functions
Fundamentals: Object, Function, Boolean, Symbol
Numbers & time: Number, BigInt, Math, Date
Text processing: String, RegExp
Indexed sequences: Array, typed arrays
Keyed collections: Map, Set, weak collections
Structured data: JSON
Error objects: Error
Async control abstraction: Promise
Internationalization: Intl
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
14 . 1
Web APIs
15 . 1
Document Object Model
(DOM)
Dynamically manipulate structured documents
15 . 2
DOM tree
The document is modeled as a tree
The tree is composed of nodes
Nodes have:
0..1 parent
0..* children
15 . 3
Nodes
Nodes are represented by JavaScript objects
We can
Navigate the tree to access nodes
Modify node attributes and properties
Add and remove nodes to the tree
15 . 4
Nodes - Navigation
document
The entry point to the DOM
document.documentElement
The root node of the document tree
document.head
The HTML head node
document.body
The HTML body node
15 . 5
Nodes - Navigation
node.childNodes
A live array-like object listing node's children
node.firstChild
The rst of node's children, or null if node has no
children
node.lastChild
The last of node's children, or null if node has no
children
node.hasChildNodes()
Returns true if node has at least one child
15 . 6
Nodes - Navigation
node.parentNode
node's parent node, or null if node is the document
root
node.nextSibling
The node immediately after node in the parent's
childNodes, or null if node is the last child
node.previousSibling
The node immediately before node in the parent's
childNodes, or null if node is the rst child
15 . 7
Nodes - Navigation
node.contains(otherNode)
Returns true if otherNode is a descendant of node
(or node itself)
node.isConnected
true if node is actually a descendant of a document
or document fragment
node.ownerDocument
The document or document fragment of which node
is a descendant
15 . 8
Nodes - Navigation
node.compareDocumentPosition(otherNode)
Returns a number describing the position of
otherNode relative to node, as bitwise composition of:
Node.DOCUMENT_POSITION_DISCONNECTED
Node.DOCUMENT_POSITION_PRECEDING
Node.DOCUMENT_POSITION_FOLLOWING
Node.DOCUMENT_POSITION_CONTAINS
Node.DOCUMENT_POSITION_CONTAINED_BY
15 . 9
Nodes - Manipulation
node.textContent RW
node.cloneNode(deep)
Return a copy of node. If deep is true, copy
15 . 10
Nodes - Manipulation
node.appendChild(newChild)
Detaches newChild from its parent
Attaches newChild to node as last child
node.insertBefore(newChild, childNode)
Detaches newChild from its parent
Attaches newChild to node as childNode's
previous sibling
15 . 11
Nodes - Manipulation
node.removeChild(oldChild)
Detaches oldChild from node
Returns oldChild
node.replaceChild(newChild, oldChild)
Detaches newChild from its parent
Attaches newChild to node in place of oldChild
Detaches oldChild from node
Returns oldChild
15 . 12
Nodes - Type
node.nodeType
A number representing node's type. One of:
Node.ELEMENT_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.COMMENT_NODE
Node.DOCUMENT_NODE
Node.DOCUMENT_TYPE_NODE
Node.DOCUMENT_FRAGMENT_NODE
15 . 13
Elements
A kind of DOM node
The ones we are usually interested in
Support a higher-level API and unique features
Attributes
Positioning
CSS style
...
15 . 14
Elements - Navigation
element.children
A live array-like object listing element's child elements
element.firstElementChild
The rst item of element.children, or null if empty
element.lastElementChild
The last item of element.children, or null if empty
element.childElementCount
The number of element's child elements
15 . 15
Elements - Navigation
node.parentElement
node's parent element, or null if node's parent is not
an element
element.nextElementSibling
The element immediately after element in the
parent's children, or null if element is the last child
element.previousElementSibling
The element immediately before element in the
parent's children, or null if element is the rst child
15 . 16
Elements - Querying
document.getElementById(id)
Returns the element with the "id" attribute equal to
id, or null if not found
element.getElementsByClassName(className)
Returns a live array-like object of element's
descendants with the "class" attribute containing
className as whole word
element.getElementsByTagName(tagName)
Returns a live array-like object of element's
descendants with html tag name equal to tagName
15 . 17
Elements - Querying
element.querySelector(cssSelector)
Returns the rst of element's descendants matching
the given cssSelector, or null if not found
element.querySelectorAll(cssSelector)
Returns an array-like object of element's descendants
matching the given cssSelector
15 . 18
Elements - Creation
document.createElement(tagName)
Returns a new disconnected element with the given
tagName
15 . 19
Elements - Attributes
Most attributes are directly accessible as properties
RW
15 . 20
Elements - Attributes
element.className RW
The full value of element's "class" attribute
element.classList
A live, rich array-like object containing all words of
element.className
element.classList.contains(class)
element.classList.add(class)
element.classList.remove(class)
element.classList.toggle(class)
element.classList.replace(oldCls, newCls)
15 . 21
Elements - Attributes
element.dataset
A live object dictionary of element's custom "data-"
attributes. The dictionary's properties
are stripped of the "data-" pre x
are converted from kebab-case to camelCase
15 . 22
Elements - Attributes
Use the following methods for advanced use cases or
to manipulate non-standard attributes
15 . 23
Elements - Attributes
element.attributes
A live array-like object of element's attributes
attribute.name
attribute's key
attribute.value
attribute's value
element.hasAttributes()
Returns true if element.attributes is not empty
15 . 24
Elements - Attributes
element.getAttributeNames()
Returns an array containing the names of element's
attributes
element.getAttribute(key)
Returns the value of element's attribute whose name
equals key
element.hasAttribute(key)
Returns true if element has an attribute whose name
equals key
15 . 25
Elements - Attributes
element.setAttribute(key, value)
Sets the value of element's attribute whose name
element.toggleAttribute(key, value?)
Toggles element's boolean attribute whose name
element.removeAttribute(key)
Removes element's attribute whose name equals key
15 . 26
Elements - Manipulation
element.innerText RW
element.insertAdjacentHTML(pos, htmlSource)
Inserts a subtree parsed from htmlSource in position
15 . 29
Elements - Manipulation
element.append(...newChildren) DOM4
15 . 30
Events
Web page objects can be target of events
Events are dispatched on various occurrences:
Loading
Rendering
Media playback
User interaction
...
15 . 31
Listeners
A listener can be attached to a target, declaring
an event type
a callback function
When an event of the requested type is dispatched to
the target, the callback is executed
15 . 32
Listener callback
function logEvent(evt) {
console.log(
evt.type,
evt.target,
evt, // many more properties
);
}
15 . 33
Declaring listeners
As HTML attributes - bad practice
<form>
<button id="log_event" onclick="logEvent(event);">
Echo text
</button>
</form>
15 . 34
Declaring listeners
As DOM element properties
const button = document.getElementById("log_event");
button.onclick = logEvent;
15 . 35
Declaring listeners
elem.addEventListener(type, cb, opts?)
Attaches a listener to target elem for event type type.
Will call function cb when the event res. opts can be:
omitted
a boolean, equivalent to setting the capture ag
an object with properties:
DOM4
15 . 36
Event bubbling
When an event occurs:
1. The innermost target is noti ed
2. The target's parent is noti ed
3. The target's ancestors are noti ed in turn,
all the way up to window
15 . 37
Capture mode
When an event occurs in capture mode:
1. The outermost capturing target is noti ed
2. Descendant capturing targets are noti ed in turn,
down to the innermost target
3. Normal event bubbling resumes from the innermost
non-capturing target
4. The target's non-capturing ancestors are noti ed in
turn, all the way up to window
15 . 38
Stopping event bubbling
<div id="outer">
OUTER
<div id="inner">INNER</div>
</div>
outer.onclick = function() {
console.log("outer");
};
inner.onclick = function(e) {
e.stopPropagation(); // IE 9+
e.cancelBubble = true; // IE 8-
console.log("inner");
};
15 . 39
Cancelling events
<a href="https://stackoverflow.com" id="link">Click me!</a>
15 . 40
Events - more APIs
elem.removeEventListener(type, cb, opts?)
Detaches an existing listener from elem, matching
type, cb and opts
elem.dispatchEvent(event)
Sends a synthetic event to elem
new CustomEvent(type, { detail })
Constructs a custom event object of a speci c type.
Custom event data passed as detail will be available
on the event object's "detail" key
15 . 41
Exercise
On button click, retrieve value from input
15 . 42