0% found this document useful (0 votes)
7K views59 pages

JS Final

Uploaded by

fotsoarole
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views59 pages

JS Final

Uploaded by

fotsoarole
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Web Application Development

INF3048 – S6

JavaScript (JS) the versatile multiparadigm web


programming language

Jacques Robin and Camilo Correa © 2023-2024


Lecture outline
1. What is JavaScript? 9. JS Variables and Scoping
2. JS programming 10. JS Expressions and
paradigms Operators
3. JS Ecosystem 11. JS Objects
4. JS Resources 12. JS Functions
5. JS Coming from Java 13. JS Prototypes
6. JS Coming from Python 14. JS Classes
7. JS Declarations and 15. JS Control statements
Statements 16. JS Modules
8. JS Values and Data Types
What is JavaScript (JS)?
 A general purpose, multiparadigm, agile programming
language that now runs everywhere!
 ECMA standard (a.k.a. ECMAScript, a.k.a., ES)
 One new version every year since v6 in 2015 (v14 in 2023)
 Monopoly on the web browsers
 Web servers: Node (install now!), Deno
 Databases: NoSQL (MongoDB) & SQL (PLV8 in PostgresQL)
 Desktops, tablets and smartphones app: Webviews
 Microcontrollers and IoT: Espruino,
https://www.manning.com/books/javascript-on-things
 Virtual Reality and Video games: PlayCanvas, Cocos
 Machine learning: TensorFlow.js
JS: Multiparadigm
The unique paradigm of
JS is prototype-based OO
Concurrent
Nowadays, all major
multiparadigm
Functional
programming languages
integrate all the others:
Imperative Event-Driven
Python, Java, C#, C++, etc.
This is because they have
Vanilla JS
historically cross-fertilized:
Class-Based JS recently added classes
Reflective
Object-
Meta Python recently added
Oriented Prototype-
asynchronous event-driven
Based
Object- Java recently added
Oriented functional
JS: The largest programming ecosystem
in the world
JS: the most relevant programming language to learn in 2023

Source: https://octoverse.github.com/2022/top-programming-languages
JS community: between 10M and 13.8M developers (source: ChatGPT )
JS: The largest programming ecosystem
in the world

Go

Dart C#, C++


C

Go
First PHP@71: Back-end web framework Laravel
First Java@87: Back-end web framework Spring-
BootFep
Express.js@106

Source: https://gitstar-ranking.com/repositories
JS: the largest programming ecosystem in the world

Over 1.8M free active JS packages available from the


Node Package Manager (NPM) repository to be reused in any
JS application through a one-line import declaration
Uber handy but, as with everything that handy, not very
secure: over 1.3K are malicious, according the White Source
https://threatpost.com/malicious-npm-packages-web-apps/17
8137/
JS resources: readings with exercises
The bible for general programming concepts illustrated in JS:
Structure and Interpretation of Computer Programs:
https://sourceacademy.org/sicpjs/index
by Abelson, Sussman G.J., Henz, Wrigstad & Sussman J.
Step-by-step, hands-on, crystal-clear guide explaining tricky JS
constructs and concepts with minimalist examples:
JavaScript Allongé: https://leanpub.com/javascriptallongesix/read
By Reg Braithwaite
The bible for practical details on JS:
Mozilla Developer Network (MDN):
https://developer.mozilla.org/en-US/docs/Web/JavaScript
JS specifically for web programming:
JavaScript from Beginner to Professional:
https://learning.oreilly.com/library/view/javascript-from-beginner/9781800
562523/
JS resources: video tutorials
Basic JS:
https://www.youtube.com/playlist?list=PL4cUxeGkcC9haFPT7J
25Q9GRB_ZkFrQAc

Advanced concepts:
https://www.youtube.com/watch?v=jnME98ckDbQ&list=PL1P
qvM2UQiMoGNTaxFMSK2cih633lpFKP

Must watch! Content on the exam syllabus


JS: Coming from nowhere
JS as a first programming language for absolute beginners:
Structure and Interpretation of Computer Programs:
https://sourceacademy.org/sicpjs/index
Not a JS-specific book
Insightfully teaches general programming concepts and
abstractions and just illustrates them in JS
It's a port to JS of an original book in which the code was in LISP
Worthy read for every programmer to:
Take a step back from syntax and the idiosyncrasies of specific
languages
See the language independent multiparadigm programming big picture
JS: Coming from Java
 Dear Java programmer, take the red pill and …

91% boilerplate
JS: Coming from Java
 Welcome to the exhilarating, free world of agile, concise,
interpreted, dynamically and weakly typed programming!
 console.log("hello world!")
JS: Coming from Java
1. No need to install anything \o/ 7. Classes are not data schemas
 Your runtime environment is the browser's  Any property (and hence method) can be added at
console runtime to objects instances of a class defined
without them
2. No need to compile anything \o/  JS objects are schemaless
 Just type expressions on the console prompt
and read their evaluation result 8. No need to define a class to just create an
 The browser calls the Just-In-Time (JIT) JS object \o/
 Create objects by a mere assignment statement
compiler automatically
3. No need to declare nor recast the types of 9. No need to define classes to have inheritance \
the variables \o/ o/
 JS objects can inherit directly from another JS object
 JS engine figures it out at runtime on its own
called their prototype
4. No need to define a class before defining a 10. However, JS:
function \o/  Still requires enclosing statement blocks with { }
 You can be agile, define stand-alone  Distinguishes variable initialization with
functions, test them, and then figure out let x=v from subsequent value
whether and how it makes sense to group re-assignment with simply x=v
them into classes Now if you can't let go of your crush on Java:
5. No need to specify the visibility of every  Don't worry
method \o/  TypeScript allows code that mimicries Java syntax to be
 Public is the default, private is just #, neither run by a JS engine
protected nor package (KISS principle)  But beware
 While syntactically it may look like Java
6. No need for interfaces \o/
 It is a bit deceitful, as semantically it is still JS
 Modules import/export encapsulate code at
 So be sure to understand JS semantics
JS: Coming from Java
JS: Coming from Python
 You should feel at ease
 Just keep on flying!
 But check:
Differences 1, 7-9 from JS
vs. Java slide
No built-in classes in JS
standard library, only
built-in objects
diff Py JS:
https://objectcomputing.co
m/resources/publications/s
ett/december-2020-compa
ring-python-and-javascript
JS: Coming from Python
Java is statically and strongly typed
Python is dynamically but strongly typed
JS is dynamically and weakly typed
Weak typing means that type coercion triggers automatically
when calling a function or operator with arguments instantiated
by variables whose current value types are inconsistent or
ambiguous w.r.t. the expected argument types
const x = "1"
const y = 2
let s = x + y
console.log(s) // "12"
 n = Number(x) + y
console.log(n) // 3
This can be disconcerting
When in doubt, test minimal expressions on the browser
JS: Coming from Python
Python dictionaries JS objects
 Similar syntax:  Similar syntax:
d = { key1: value1, …, keyN: valueN } o = { key1: value1, …, keyN: valueN }
 Duplicate keys automatically removed  Duplicate keys automatically removed
 Values accessed by [ ] only:  Values accessed by either [ ] or dot:v =
v = d[keyK] # valueK o.keyK // valueK
 Keys must be immutables, i.e., v = o['keyK'] // valueK, allows expressions
Booleans, integers, floats, strings and as keys
tuples  Keys must be either identifiers,
strings, numbers or Booleans but the
latter two only by being coerced into
a string
 JS also has a built-in Map object
which differs subtly from the plain JS
Object
 In particular, a Map can have
reference type objects as keys
JS: Coming from Python
Due to its amazing evolution
over almost three decades
From a tiny scripting language
to make small changes in the browser to
web pages generated on a server
To a multiparadigm universal application
language running everywhere with the
largest developer community in the world
JS breaks the Zen of Python aphorism:
"There should be one – and preferably only one
– obvious way to do it"
In JS, there are usually many ways to do a given thing:
 Functional vs OO
 Prototypes vs classes
 Explicitly vs implicily typed
 Vanilla vs frameworks
 Synchronous vs asynchronous
 The community is fragmented in terms of these alternatives
This is what makes it hard to truly master
JS: Declarations vs. Statements

A JS Script is an ordered set of declarations and statements


Declarations declare variables, functions, classes and modules
JS values
Almost all JS values are
objects
Except null and undefined
JS objects are dynamic bags
of properties
All JS objects inherit
properties from their
prototype object
JS methods are just object
properties whose value is a
function
JS objects subcategorize
into:
Primitive vs. Reference objects
Built-In vs. User defined
objects
JS data types

typeof: built-in operator returning the type of a value or variable


Not always aligned with the built-in prototype object
 Arrays and dates values are instances of their respective specialized prototypes, yet they are all of type
object
 The null value has type object but no prototype
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
JS: value vs. reference types
Variables assigned to a value type Variables assigned to a reference type
 Are directly associated with their  Are indirectly associated with their
primitive value on the stack area of object value through a pointer
memory  The variable is associated with the
 When multiple variables are pointer on the stack
assigned to the same primitive  That pointer points to the object value
value, each holds it own copy of it stored on the heap area of memory
on the stack area of memory  When multiple variables are assigned to
the same object value, they all points to
a shared copy of the object
 When a property inside the object value
is changed from one variable, it thus
also automatically changes for the other
variable
 But when one variable is reassigned to
another pointer, then the other variables
that pointed to the same object value
are not affected
JS: value vs. reference types

Source: The Net Ninja:


https://www.youtube.com/watch?v=X0ipw1k7ygU&list=PL4cUxe
GkcC9haFPT7J25Q9GRB_ZkFrQAc&index=5
JS: value vs. reference types
Variables assigned to a value type Variables assigned to a reference type
 let n = 1;  let o1 = {n: 1}
 n // 1  let o2 = o1
 let m = n  o1 // Object {n: 1}
 m // 1  o2 // Object {n: 1}
 n=2  o1.n = o1.n + 1 // 2
 n // 2  o1 // Object {n: 2}
  o2 // Object {n: 2}
m // 1
 o1 = {n: 1}
  o1 // Object {n: 1}
incr = (age) => ++age
 o2 // Object {n: 2}
 myAge = 20 // 20
 incr(myAge) // 21
 incrAge = (p) => ++p.age
 myAge = 20 // 20
 p1 = {age: 20} // Object {age:20}
 p2 = p1 // Object {age:20}
 incrAge(p1)
 p1 // Object {age:21}
 p2 // Object {age:21}
JS: variable scoping
Variables can be declared with let or const and then assigned a value or (best)
declared with an initial value to avoid temporary undefined state
Variables declared with let or const are block scoped
Example:
https://gitlab.esiea.fr/web-programming-instructors/js-examples/-/tree/main/Variab
leScope

You might find legacy code declaring variables with var


 It has global or function scope and is error prone
 When you do check:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
let allows redefining the reference to the variable
const does not, but nevertheless allows object property mutations
const o = { k1: "hello "}
console.log(o) // { k1: "hello" }
o.k2 = "world"
console.log(o) // { k1: "hello", k2: "world' '}
More:
 let: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
JS Primitive Types: Booleans and Numbers
JS Booleans:
When an expression in a place where a
Boolean is expected (e.g., the condition
of an if statement) returns a non-
Boolean value
JS coerces the value to true or false
rather than raising an exception
Values coerced to false are dubbed
"falsy"
Values coerced to true are dubbed
"truthy"
JS numbers:
No integer vs. float distinction
JS equality operators: == and ===
===: strict equality: equality of both value and type
==: equality modulo type coercion
See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe
rence/Operators/Equality
Primitive type instances can be created in 3 ways:
Assignment to literal: x1 = 2
Assignment to result of constructor function of its prototype object:
x2 = Number(2)
New operator: x3 = new Number(2)
They are all thankfully ==
Also, x1 === x2 // true
But beware, x3 === x1 // false and x3 === x2 // false
since x3 is a wrapper object while x1 and x2 are naked primitive values
JS primitive data types: null vs. undefined
null: absence of a value
undefined: absence of an object

// foo does not exist. It is not defined and has never been initialized:
foo; // ReferenceError: foo is not defined
// foo is known to exist now, but it has no type or value:
const foo = null;
foo; //null

typeof null; // "object" (not "null" for legacy reasons)


typeof undefined; // "undefined"
null === undefined; // false
null == undefined; // true
null === null; // true
null == null; // true
!null; // true
Number.isNaN(1 + null); // false

JS primitive types: strings vs. symbols
Symbols: unique ID creator
Handy to guarantee uniqueness of keys in an object
const sy1 = Symbol()
const sy2 = Symbol("foo")
const sy3 = Symbol("foo")
sy2 === sy3 // false
const sy4 = new Symbol("bar") // TypeError: Symbol is not a constructor
sy4 // undefined
In contrast:
const st2 = "foo" // "foo"
const st3 = "foo" // "foo"
st2 === st3 // true
const st4 = new String("foo") // String { "foo" }
st2 == st4 // true
st2 === st4 // false
JS reference data types: arrays
Creation by literal value assignment:
x = "foo"
y = "baz"
a = [x , "bar", y]
Instantiates the array prototype object
Items are the special properties of an array as a JS object
Indexed by non-negative integers with first item at [0]
Variable length
Heterogeneous content
x = "world" // "world"
a = ["hello", x + "!"] // Array["hello", "world!"]
a[2] // undefined
a[2+2] = "what's up?"
// Array(4) ["hello", "world!", <2 empty slots>, "what's up?"]
JS Expressions and Operators
JS: Object creation
Declaring variable with object default value:
let o1 = {a: 1} // undefined
o1 // Object {a: 1}
o1 = "foo" // "foo"
const o2 = {b:2, c: 3} // undefined
o2 = "bar" // invalid assignment to const 'o2'
o2.b = 4 // 4
o2 // Object { b: 4, c: 3 }
Assigning variable to object literal:
o3 = {c : 3} // Object {c: 3}
Call to constructor function Object() of built-in Object prototype
o4 = Object({d: 4}) // Object {d: 4}
Call to Object(o) with new operator:
o5 = new Object({e: 5}) // Object {e: 5}
Call to static method create(p) of built-in Object() constructor of built-in
Object prototype:
o6 = Object.create(Object} // Object{}
o6.f = 6
JS imperative object operators
Property assignment:
With dot:
o2.b = 6 // 6
o2 // Object {b: 6, c: 3}
With brackets:
o2['b'] = 7
o2 // Object {b: 7, c 3}
o2[a] = 8 // a is not defined
Property deletion:
delete o2['b'] // true
o2 // Object {c: 3}
delete o2['c'] // true
o2 // Object { }
JS declarative object operators
k in o: returns true if object o contains a property keyed by k
const o = {a: 1, b: 2} // undefined
o // Object {a:1, b:2}
'a' in o // true
'c' in o // false
Instanceof: o instanceof Object // true
Optional chaining operator ?: avoid errors when followng . or []
path along object property chains
const o = {a:1} // undefined
o // Object {a: 1}
obc = o.b.c // error b is undefined
obc = o.b?.c // undefined
JS destructuring assignment
Arrays Object literals
 let x, y, z, r  let o = {a:1, b: {c:2}, d: {e:3}}
 [x, [y, z], …r] = [1, [2, 3], [4, 5], 6]  let {a: x, b: {c: y}, d: z} = o
 x // 1  x // 1
 y // 2  y // 2
 z // 3  z // Object {e:3}
 r // Array(2) [[4,5], 6]  let u, v, w
 ( {a: u, b: {c: v}, d: w} = o)
// parentheses needed to avoid syntax error
 u // 1
 v // 2
 w // Object {e:3}

More:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Opera
JS Functions: Declaration vs. Expressions
Stand-alone declaration:
function <function-name> (<parameter-list1>) { <statements> }
Function expression defining function as left-hand side of an
assignment statement:
<variable-name> = function <optional-function-name> (<parameter-list>)
{ <statements> }
The <variable-name> becomes the <function-name> to call the function
Function call expressions (including expression statements)
<function-name> (<argument-list>)
When a call to function f precedes its definition in a JS script:
If the function was defined in a variable assignment, JS throws a
ReferenceError: f is not defined
If the function was defined by a stand-alone declaration, JS hoists it
above the call to avoid such error
Best practice: define your function before calling them
JS Functions: Declaration vs. Expressions
Each parameter in parameter-list is replaced by the value, rather
than a reference to, the corresponding argument in argument-list
Thus:
Parameter value full re-assignment inside the function body block are
scoped to the block and lost in the containing scope of the function call
However, partial re-assignment of an object parameter property is
visible in the containing scope of the function call, since object values
are pointers
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-examples/-/tree/
main/Functions
More:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Gui
de/Functions
JS high-order functions and callbacks
As in all functional languages, in JS, a function can be:
Passed as parameter to another functions
Returned as result to another functions
In such case:
The function passed as parameter is called a callback function
The function that receives the callback as parameter is called a high-
order function
This is the root of the power of functional programming
JS Functions: Factories and Constructors
Factories and constructors: functions which purpose is to create objects
In JS they can be stand-alone functions, not necessarily a method of an
object or class
All built-in JS prototypes come with a constructor function to create
objects from the prototype
Examples:
let o = {p:1}, a = [1,2], s = "hi"
o // Object {p:1}
a // Array [1,2]
s // "hi"
s.__proto__ // String { "" }
Standard functions creating objects are called factories (from the OO
language independent factory design pattern)
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-examples/-/tree
/main/Constructors
JS Functions: Factories and Constructors
JS provides two keywords to build objects in a more class-
based OO syntax, even without classes:
this: a reference to an object in a function definition which value
depends on the execution context of the function (handy but tricky)
new: an operator relating on its left side an object to be created and on
its right side a call to a constructor function using this in its definition
By convention constructor function names are uppercased
new binds the this reference to the object being created
this:
Note that in JS, any function f can be called on any object o,
independently on f's definition context, once it's been dynamically
added to o as a property
By default, this binds to the call context object of f, rather than to its
definition context
If this call context is not a user-defined object, then it is the global
context, which, in a browser is the window object
JS Functions: Arrow syntax
More concise syntax for defining anonymous functions in
expressions
Replace function keyword before parameter list,
by => keyword after parameter list
Hence: <variable-name> = (<parameter-list>) => { <statements> }
instead of:
<variable-name> = function <optional-function-name> (<parameter-list>)
{ <statements> }
Furthermore:
( ) around single parameter can be elided
If function block statements can be a single expression statement, then
{ } block delimiter and return keyword can be elided as well
JS Functions: Arrow syntax
Arrow syntax:
Cannot be used for constructor or factory functions, i.e., functions made
to create objects (using or not using new operator, respectively) since
such functions cannot be anonymous
Should not be used:
 To define an object method, because it does not bind the this variable to the
containing object, but rather to the containing scope of the object
To define a function in a statement that attaches it to a prototype
To define an event handler callback function passed to the addEventListener()
method of the EventTarget interface of the DOM API
For detailed explanations watch:
https://www.youtube.com/watch?v=ajTvmGxWQF8&list=PL1P
qvM2UQiMoGNTaxFMSK2cih633lpFKP&index=7
JS Functions: Methods
In JS, a method is just a function attached to an object
It can be associated to an object:
In an object creation statement with an object literal expression using
with the full function syntax
In an object creation statement with the object literal expression using
the special method elided syntax
By a property assignment statement of a created object to a function
created elsewhere
this is tricky:
An object alone and an arrow function method inside of it do not bind
this to the object
But a method with function keyword or elided syntax inside an object
does
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-exampl
es/-/tree/main/Methods
JS Closures
In JS, when the definition of an outer function outerF() contains
the definition of an inner function innerF()
the variables available to innerF() by being in its lexical scope in
that definition context
remain available to innerF() in another context, after outerF() has
returned
innerF() together with its creation context is called the closure
innerF()
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-exampl
es/-/tree/main/Closures
JS prototype inheritance
Much like in class-based OO, any object has a class from which it was
constructed and inherits its initial properties
In prototype-based OO, any object has another object, called its prototype,
from which it was constructed and inherits its initial properties
At the top of the JS prototype generalization inheritance hierarchy lays the
built-in JS Object prototype which own prototype is null, which in turns has
no prototype
The prototype of a JS object is reflectively available at the __proto__ property
(a.k.a [[Prototype]])
__proto__ is not to be confused with the prototype property which does not
belong to an object but to the constructor function used to create it
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-examples/-/tree/mai
n/Prototypes

More:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_
the_prototype_chain
JS classes

In JS, classes are syntactic sugar over constructor functions


Under the hood, JS implements class to subclass and class to object
inheritance by object-to-object prototype inheritance
See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
JS Control statements

Very similar to other programming languages


Note the difference between:
 The conditional statement:
if (<condition-expression>) { <if-true-statement> } else { <if-false-statement> }
 The conditional expression:
if <condition-expression> ? <if-true-expression> : <if-false-expression>
JS Loops

 for-in to loop over the keys of an object's properties


 for-of to iterate over the values of an object's properties
 Example:
 const a = [3, 5, 7]
 // for (const k in a) { console.log(k) }
 // for (const v of a) { console.log(v) }
 Use for(<beforeExp>, <condExp>, <afterExp>) for all other cases
 while executes statement after condition is tested
 do-while executes statement before condition is tested
JS exceptions
Classic throw, try, catch triplet of blocks
Very similar to other programming languages
Example:
function getRectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
throw new Error('Parameter is not a number!')
}
}

try {
getRectArea(3, 'A')
}
catch (e) {
console.error(e) // Expected output: Error: Parameter is not a number!
}
JS built-in utility objects
Date:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glo
bal_Objects/Date

Math:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glo
bal_Objects/Math
JSON

JS Object Literal JSON


 Aggregates data and behavior  A special kind of single quoted string
 Keys can be single quoted or double  Serializes only data not behavior
quoted strings, symbols or even  Functions are not stringified
numbers and Boolean type coerced to  Keys must be double quoted strings
string  String values must be double quoted
 Accepts trailing commas
 Prohibits trailing commas
 Numbers can have leading zero and
 Numbers can't have leading zeros
be NaN or infinity
and cannot be NaN nor infinity
 Undefined has no JSON serialization
JS modules
Decompose JS application
in multiple modules
Each module is contained
in a different file
It starts by a sequence
of import declarations
allowing the use in the
importing module of
variables, functions and
classes declared in and
exportable from other
modules
It contains one or more export
declarations allowing some
variables, functions and classes
declared in it to be imported in
other modules
When the href attribute of an html <script> tag points to a module file, the tag must
also contain a "type = module" attribute
The .js extension at the end of the imported file path is required
JS: import/export variants
Import variants Export variants
// Named imports: // Named exports: any number per module
 import { nameExport1, …, nanedExportN }  export default nameExport
from "module-name" // export features declared elsewhere
// Default imports:  export { myFunction2, myVariable2 };
 import defaultExport from // export individual feature
"module-name"  export let myVariable = Math.sqrt(2);
// Namescape import  export function myFunction() { */ … */ }
 import * as name from "module-name"  export class MyClass { */ … */ }
// Side-effect import
 import "module-name" // Default exports: only one per module
// export feature declared elsewhere as default
 export default myFunction;
// export individual features as default
 export default function () { /* … */ }
 export default class { /* … */ }
JS module import/export examples
Most basic example:
https://gitlab.esiea.fr/web-programming-instructors/js-exampl
es/-/tree/main/Modules

More on modules: More on modules:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Gui
de/Modules

Import kinds and syntaxes:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe
rence/Statements/import

Export kinds and syntaxes:


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe
rence/Statements/export
JS proxies
JS provides as built-in a Proxy object to implement the aspect-oriented
meta-programming proxy design pattern
A JS Proxy instance
created by a
new Proxy(<target>, <handler>)
expression
weaves a wrapper between
a target object and its clients
to perform some pre and/or
post-processing implementing
an aspect (e.g., logging,
parameter validation,
security check, reactivity, etc.)
transparently to the
client-target interface
JS Reflect
A built-in JS Object to work with JS Proxy handlers
It has no constructor and all its methods are static
It has one such method for each method of the JS Object Proto Object at
the root of the prototype chain
It allows intercepting call to those methods on objects instance of the
prototype
Example of Proxy with Reflect:
https://gitlab.esiea.fr/web-programming-instructors/js-examples/-/tree/m
ain/Proxies

More on Proxies:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob
al_Objects/Proxy

More on Reflect:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Glob
al_Objects/Reflect
JS generators and iterators
The function* keyword defines a generator function
It contains yield expressions of the form:
yield <JS expression>
each yield expression represents one possible value in finite domain
It may also contain a return <JS expression>
However, the value returned by calling the generator function
is not the value of its return expression
Rather, it is a generator object inheriting from the built-in
generator prototype that has built-in methods:
next() which call for the Nth time, returns an object of the form
{value: v, done: false} in which v is the value of the Nth yield expression of
the generator function which call returned the generator object
return(v) to return an object of the form {value: v, done: true}
throw(e) to throw error e when called in a try-catch statement
JS generators and iterators
The generator object:
Encapsulates the values of a finite domain
Implements the iterator protocol providing iterative access to these
values through successive calls to the next() method while remembering
which values was last yielded by the last such call
Examples:
https://gitlab.esiea.fr/web-programming-instructors/js-exampl
es/-/tree/main/GeneratorFunctions
JS generators and iterators

You might also like