JavaScript Essentials Overview
JavaScript Essentials Overview
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++) {
[Link]("number " + i);
}
Java
for (int i = 0; i < 10; i++) {
[Link]("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++) {
[Link]("number " + i);
}
5 . 10
... and semicolons
for (var i = 0; i < 10; i++) {
[Link]("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++){[Link](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
[Link](5 * 10);
8 . 3
A simple example
[Link](5 * 10);
A statement...
8 . 4
A simple example
[Link](5 * 10);
8 . 5
A simple example
[Link](5 * 10);
An expression
8 . 6
A simple example
[Link](5 * 10);
8 . 7
A simple example
[Link](5 * 10);
8 . 8
A simple example
[Link]( 50 );
8 . 9
A simple example
[Link]( 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;
[Link](x, y, z); // prints: 7 8 5
}
[Link](x, y, z); // prints: 3 8 5
9 . 5
Function declaration
function sum(a, b) {
return a + b;
}
function logInfo(message) {
[Link]("INFO", message);
}
9 . 6
if / else
if (z > x) {
[Link]("Big z");
}
if (x > 20) {
[Link]("Very big x");
} else if (x > 10) {
[Link]("Big x");
} else {
[Link]("Small x");
}
9 . 7
switch / case
switch (name) {
case "Jim":
case "Joe":
[Link]("Hey, man!");
break;
case "Jane":
case "Jill":
[Link]("Good morning, Madam");
break;
default:
[Link]("Hello dear guest");
}
9 . 8
Loops: while and do / while
while (x > 0) {
[Link]("until x becomes zero", x--);
}
do {
[Link]("at least once")
} while (false);
9 . 9
Loops: for
for (var i = 0; i < 10; i++) {
[Link]("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;
[Link]; // TypeError: nobody is null
9 . 13
Errors can be recovered by catching them
try {
const nobody = null;
[Link];
} catch (e) {
[Link]([Link]); // 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,
"[Link]": 2, // Key is not a valid name (contains .)
},
};
10 . 3
Property access
[Link]; // "Jerry"
jerry["age"]; // 33
[Link]; // 5
const k = "JavaScript";
[Link][k]; // 5
[Link]; // undefined
10 . 4
[Link] += 1; // set property 'age'
[Link]; // 34
10 . 5
Null pointer dereferencing
let jimmy;
[Link]([Link]); // TypeError: jimmy is undefined
[Link](jimmy && [Link]); // would print: undefined
10 . 6
Optional chaining operator ES2020
let jimmy;
[Link](jimmy?.name); // prints: undefined
10 . 7
Object references
Objects are referenced by variables
const me = jerry;
[Link] = 35;
[Link]; // 35
10 . 8
Loops: for / in
Loop over an object's keys
for (let k in jerry) {
[Link](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
[Link]; // 4
fruit[4]; // undefined
[Link]; // undefined;
10 . 12
fruit[0] = "Kiwi"; // replace element
fruit; // [Kiwi, Orange, Peach, Mango]
fruit[7] = "Pineapple";
fruit; // [Kiwi, Orange, Peach, Mango, Coconut, , , Pineapple]
[Link]; // 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
[Link]("Hello, World!");
}
12 . 2
Invocation
12 . 3
Parameters
function sayHello(from, to) {
[Link](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) {
[Link](helloTo(who));
}
12 . 11
Functions are values, too
typeof hello === "function";
12 . 12
Higher order functions
function doTwice(action) {
action();
action();
}
function printMessage() {
[Link]("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 < [Link]; i++) {
if (predicate(array[i]))
result[[Link]] = 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() {
[Link]("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
[Link] APIs
Server-side functionality
De ned by the [Link] 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
[Link]/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
[Link]
The root node of the document tree
[Link]
The HTML head node
[Link]
The HTML body node
15 . 5
Nodes - Navigation
[Link]
A live array-like object listing node's children
[Link]
The rst of node's children, or null if node has no
children
[Link]
The last of node's children, or null if node has no
children
[Link]()
Returns true if node has at least one child
15 . 6
Nodes - Navigation
[Link]
node's parent node, or null if node is the document
root
[Link]
The node immediately after node in the parent's
childNodes, or null if node is the last child
[Link]
The node immediately before node in the parent's
childNodes, or null if node is the rst child
15 . 7
Nodes - Navigation
[Link](otherNode)
Returns true if otherNode is a descendant of node
(or node itself)
[Link]
true if node is actually a descendant of a document
or document fragment
[Link]
The document or document fragment of which node
is a descendant
15 . 8
Nodes - Navigation
[Link](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
[Link] RW
[Link](deep)
Return a copy of node. If deep is true, copy
15 . 10
Nodes - Manipulation
[Link](newChild)
Detaches newChild from its parent
Attaches newChild to node as last child
[Link](newChild, childNode)
Detaches newChild from its parent
Attaches newChild to node as childNode's
previous sibling
15 . 11
Nodes - Manipulation
[Link](oldChild)
Detaches oldChild from node
Returns oldChild
[Link](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
[Link]
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
[Link]
A live array-like object listing element's child elements
[Link]
The rst item of [Link], or null if empty
[Link]
The last item of [Link], or null if empty
[Link]
The number of element's child elements
15 . 15
Elements - Navigation
[Link]
node's parent element, or null if node's parent is not
an element
[Link]
The element immediately after element in the
parent's children, or null if element is the last child
[Link]
The element immediately before element in the
parent's children, or null if element is the rst child
15 . 16
Elements - Querying
[Link](id)
Returns the element with the "id" attribute equal to
id, or null if not found
[Link](className)
Returns a live array-like object of element's
descendants with the "class" attribute containing
className as whole word
[Link](tagName)
Returns a live array-like object of element's
descendants with html tag name equal to tagName
15 . 17
Elements - Querying
[Link](cssSelector)
Returns the rst of element's descendants matching
the given cssSelector, or null if not found
[Link](cssSelector)
Returns an array-like object of element's descendants
matching the given cssSelector
15 . 18
Elements - Creation
[Link](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
[Link] RW
The full value of element's "class" attribute
[Link]
A live, rich array-like object containing all words of
[Link]
[Link](class)
[Link](class)
[Link](class)
[Link](class)
[Link](oldCls, newCls)
15 . 21
Elements - Attributes
[Link]
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
[Link]
A live array-like object of element's attributes
[Link]
attribute's key
[Link]
attribute's value
[Link]()
Returns true if [Link] is not empty
15 . 24
Elements - Attributes
[Link]()
Returns an array containing the names of element's
attributes
[Link](key)
Returns the value of element's attribute whose name
equals key
[Link](key)
Returns true if element has an attribute whose name
equals key
15 . 25
Elements - Attributes
[Link](key, value)
Sets the value of element's attribute whose name
[Link](key, value?)
Toggles element's boolean attribute whose name
[Link](key)
Removes element's attribute whose name equals key
15 . 26
Elements - Manipulation
[Link] RW
[Link](pos, htmlSource)
Inserts a subtree parsed from htmlSource in position
15 . 29
Elements - Manipulation
[Link](...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) {
[Link](
[Link],
[Link],
evt, // many more properties
);
}
15 . 33
Declaring listeners
As HTML attributes - bad practice
<form>
<button id="log_event" > Echo text
</button>
</form>
15 . 34
Declaring listeners
As DOM element properties
const button = [Link]("log_event");
[Link] = logEvent;
15 . 35
Declaring listeners
[Link](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>
[Link] = function() {
[Link]("outer");
};
[Link] = function(e) {
[Link](); // IE 9+
[Link] = true; // IE 8-
[Link]("inner");
};
15 . 39
Cancelling events
<a href="[Link] id="link">Click me!</a>
15 . 40
Events - more APIs
[Link](type, cb, opts?)
Detaches an existing listener from elem, matching
type, cb and opts
[Link](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