JS Final
JS Final
INF3048 – S6
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
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
Advanced concepts:
https://www.youtube.com/watch?v=jnME98ckDbQ&list=PL1P
qvM2UQiMoGNTaxFMSK2cih633lpFKP
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
// 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
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
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
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