1 02 Javascript Objects Functions
1 02 Javascript Objects Functions
and Functions
“The” language of the Web
Fulvio Corno
Luigi De Russis
Enrico Masala
2
Applicazioni Web I - Web Applications I - 2021/2022
JavaScript: The Definitive Guide, 7th Edition
Chapter 5. Objects
OBJECTS
3
Applicazioni Web I - Web Applications I - 2021/2022
Big Warnings (a.k.a., forget Java objects)
• In JavaScript, Objects may exist without Classes
– Usually, Objects are created directly, without deriving them from a Class
definition
• In JavaScript, Objects are dynamic
– You may add, delete, redefine a property at any time
– You may add, delete, redefine a method at any time
• In JavaScript, there are no access control methods
– Every property and every method is always public (private/protected don’t exist)
• There is no real difference between properties and methods (because of
how JS functions work)
4
Applicazioni Web I - Web Applications I - 2021/2022
Object
• An object is an unordered collection of properties
– Each property has a name (key), and a value
• You store and retrieve property values, through the property names
• Object creation and initialization:
let point = { x: 2, y: 5 };
let book = {
author : "Enrico", Object literals syntax:
title : "Learning JS", {"name": value,
for: "students", "name": value, }
pages: 520, or:
}; {name: value,
name: value, }
5
Applicazioni Web I - Web Applications I - 2021/2022
Object Properties
Property names are … Property values are …
• Identified as a string • Reference to any JS value
• Must be unique in each object • Stored inside the object
• Created at object initialization • May be primitive types
• Added after object creation • May be arrays, other objects, …
– With assignment – Beware: the object stores the
• Deleted after object creation reference, the value is outside
– With delete operator • May also be functions (methods)
6
Applicazioni Web I - Web Applications I - 2021/2022
The . dot notation and omitting the quotes are
Accessing properties allowed when the property name is a valid
identifier, only.
book.title or book['title']
book['my title'] and not book.my title
• Dot (.) or square brackets [] notation
let book = {
author : "Enrico",
title : "Learning JS",
for: "students",
pages: 340,
"chapter pages": [90,50,60,140]
};
8
Applicazioni Web I - Web Applications I - 2021/2022
Computed property names
• Flexibility in creating object • Beware of quotes:
properties – book["title"] -> property called
– {[prop]:value} -> creates an title
object with property name equal to • Equivalent to book.title
the value of the variable prop – book[title] -> property called
– [] can contain more complex with the value of variable title (if
expressions: e.g., i-th line of an exists)
object with multiple "address" • If title=="author", then equivalent
properties (address1, address2, …): to book["author"]
person["address"+i] • No equivalent in dot-notation
• Using expressions is not
recommended…
9
Applicazioni Web I - Web Applications I - 2021/2022
Property access errors
• If a property is not defined, the (attempted) access returns undefined
• If unsure, must check before accessing
– Remember: undefined is falsy, you may use it in Boolean expressions
10
Applicazioni Web I - Web Applications I - 2021/2022
Iterating over properties
• for .. in iterates over the properties
for( let a in {x: 0, y:3}) { let book = {
console.log(a) ; author : "Enrico",
} pages: 340,
chapterPages: [90,50,60,140],
x
};
y
for (const prop in book)
console.log(`${prop} = ${book[prop]}`);
author = Enrico
pages = 340
chapterPages = 90,50,60,140
11
Applicazioni Web I - Web Applications I - 2021/2022
Iterating over properties
• All the (enumerable) properties names (keys) of an object can be
accessed as an array, with:
[ 'author', 'pages' ]
– let keys = Object.keys(my_object) ;
• All pairs [key, value] are returned as an array with:
– let keys_values = Object.entries(my_object)
[ [ 'author', 'Enrico' ], [ 'pages', 340 ] ]
12
Applicazioni Web I - Web Applications I - 2021/2022
Copying objects
let book = { let book = {
author : "Enrico", author : "Enrico",
pages: 340, pages: 340,
}; };
13
Applicazioni Web I - Web Applications I - 2021/2022
Object.assign
• let new_object = Object.assign(target, source);
• Assigns all the properties from the source object to the target one
• The target may be an existing object
• The target may be a new object: {}
• Returns the target object (after modification)
14
Applicazioni Web I - Web Applications I - 2021/2022
Beware! Shallow copy, only
let book = {
author : "Enrico",
pages: 340,
};
let study = {
topic: "JavaScript",
source: book,
};
15
Applicazioni Web I - Web Applications I - 2021/2022
Merge properties (on existing object)
• Object.assign(target, source, default values, ..);
let book = {
author : "Enrico",
pages: 340,
};
16
Applicazioni Web I - Web Applications I - 2021/2022
Merge properties (on new object)
• Object.assign(target, source, default values, ..);
let book = {
author : "Enrico",
pages: 340,
};
17
Applicazioni Web I - Web Applications I - 2021/2022
Copying with spread operator (ES9 – ES2018)
18
Applicazioni Web I - Web Applications I - 2021/2022
Checking if properties exist
• Operator in
– Returns true if property is in the object. Do not use with Array
let book = { const v=['a','b','c’];
author : "Enrico",
pages: 340, console.log('b' in v);
};
console.log('author' in book);
delete book.author; console.log('PI' in Math);
console.log('author' in book);
true false
false true
19
Applicazioni Web I - Web Applications I - 2021/2022
Object creation (equivalent methods)
• By object literal: const point = {x:2, y:5} ;
Preferred
• By object literal (empty object): const point = {} ;
• By constructor: const point = new Object() ;
• By object static method create:
const point = Object.create({x:2,y:5}) ;
• Using a constructor function
20
Applicazioni Web I - Web Applications I - 2021/2022
JavaScript: The Definitive Guide, 7th Edition
Chapter 7. Functions
FUNCTIONS
21
Applicazioni Web I - Web Applications I - 2021/2022
Functions
• One of the most important elements in JavaScript
• Delimits a block of code with a private scope
• Can accept parameters and returns one value
– Can also be an object
• Functions themselves are objects in JavaScript
– They can be assigned to a variable
– Can be passed as an argument
– Used as a return value
22
Applicazioni Web I - Web Applications I - 2021/2022
Declaring functions: 3 ways
1) Classic
function do(params) {
/* do something */
}
23
Applicazioni Web I - Web Applications I - 2021/2022
Classic functions
let n = square(4) ;
After
execution
24
Applicazioni Web I - Web Applications I - 2021/2022
Parameters
• Comma-separated list of parameter names
– May assign a default value, e.g., function(a, b=1) {}
• Parameters are passed by-value
– Copies of the reference to the object
• Parameters that are not passed in the function call get the value
‘undefined’
• Check missing/optional parameters with:
– if(p===undefined) p = default_value ;
– p = p || default_value ;
25
Applicazioni Web I - Web Applications I - 2021/2022
Variable number of parameters
• Syntax for functions with variable number of parameters, using the ...
operator (called “rest”)
function fun (par1, par2, ...arr) { }
• The “rest” parameter must be the last, and will deposit all extra arguments
into an array
function sumAll(initVal, ...arr) {
let sum = initVal;
for (let a of arr) sum += a;
return sum;
}
sumAll(0, 2, 4, 5); // 11
26
Applicazioni Web I - Web Applications I - 2021/2022
Declaring functions: 3 ways
1) Classic 2a) Function expression
27
Applicazioni Web I - Web Applications I - 2021/2022
Function expression: indistinguishable
function square(x) {
let y = x * x ;
return y ;
}
28
method callback
Applicazioni Web I - Web Applications I - 2021/2022
Declaring functions: 3 ways
1) Classic 2a) Function expression
29
Applicazioni Web I - Web Applications I - 2021/2022
Arrow Function: just a shortcut
function square(x) {
let y = x * x ;
return y ;
}
let n = fourth(4) ;
30
Applicazioni Web I - Web Applications I - 2021/2022
Parameters in arrow functions
const fun = () => { /* do something */ } // no params
31
Applicazioni Web I - Web Applications I - 2021/2022
Return value
• Default: undefined
• Use return to return a value
• Only one value can be returned
• However, objects (or arrays) can be returned
const fun = () => { return ['hello', 5] ; }
const [ str, num ] = fun() ;
console.log(str) ;
32
Applicazioni Web I - Web Applications I - 2021/2022
Nested functions
• Function can be nested, i.e., defined within another function
function hypotenuse(a, b) {
const square = x => x*x ; => Preferred in nested functions
return Math.sqrt(square(a) + square(b));
}
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
• The inner function is scoped within the external function and cannot be called
outside
• The inner function might access variables declared in the outside function
33
Applicazioni Web I - Web Applications I - 2021/2022
Closure: definition (somewhat cryptic)
https://medium.com/@vvkchandra/learn-javascript-
closures-through-the-laws-of-karma-49d32d35b3f7
34
Applicazioni Web I - Web Applications I - 2021/2022
Closures
"use strict" ;
• JS uses lexical scoping function greeter(name) {
– Each new functions defines a scope const myname = name ;
for the variables declared inside
const hello = function () {
– Nested functions may access the return "Hello " + myname ;
scope of all enclosing functions }
Warning: not
• Every function object remembers return hello ;
return hello() ;
}
the scope where it is defined,
even after the external function const helloTom = greeter("Tom") ;
const helloJerry = greeter("Jerry") ;
is no longer active → Closure
console.log(helloTom()) ;
console.log(helloJerry()) ;
35
Applicazioni Web I - Web Applications I - 2021/2022
Closures
"use strict" ;
• hello accesses the variable
function greeter(name) {
myname, defined in the outer scope const myname = name ; greeter
• The function is returned (as scope
helloTom or helloJerry) const hello = function () {
return "Hello " + myname ;
• Each of the functions “remembers” } hello
scope
the reference to myname, when it
return hello ;
was defined }
• The variable myname goes out of
const helloTom = greeter("Tom") ;
scope, but is not destroyed const helloJerry = greeter("Jerry") ;
– Still accessible (referred) by the hello
functions. console.log(helloTom()) ;
console.log(helloJerry()) ;
36
Applicazioni Web I - Web Applications I - 2021/2022
Using closures to emulate objects
"use strict" ; const count1 = counter() ;
console.log(count1()) ;
function counter() { console.log(count1()) ;
let value = 0 ; console.log(count1()) ;
return getNext ; 1
} 2
3
1
2
3
37
Applicazioni Web I - Web Applications I - 2021/2022
Using closures to emulate objects (with methods)
"use strict"; let c = counter(), d = counter();
// Create two counters
function counter() {
c.count()
let n = 0;
// => 0
38
Applicazioni Web I - Web Applications I - 2021/2022
Immediately Invoked Function Expressions (IIFE)
• Functions may protect the scope ( function() {
let a = 3 ;
of variables and inner functions console.log(a) ;
} ) () ;
• May declare a function
– With internal variables
let num = ( function() {
– With inner functions let a = 3 ;
return a ;
– Call it only once, and discard } ) () ;
everything
https://flaviocopes.com/javascript-iife/
https://medium.com/@vvkchandra/essential-
javascript-mastering-immediately-invoked-
function-expressions-67791338ddc6
39
Applicazioni Web I - Web Applications I - 2021/2022
Using IIFE to emulate objects (with methods)
"use strict"; console.log(c.count());
console.log(c.count());
const c = ( c.reset();
console.log(c.count());
function () {
console.log(c.count());
let n = 0;
return {
count: function () {
0
return n++; }, 1
reset: function () { 0
n = 0; } 1
};
})();
40
Applicazioni Web I - Web Applications I - 2021/2022
Construction functions
• Define the object type
– Use a capital initial letter
– Set the properties with the keyword this
• Create an instance of the object with new
41
Applicazioni Web I - Web Applications I - 2021/2022
JavaScript: The Definitive Guide, 7th Edition
Chapter 9.4 Dates and Times
Day.js
https://day.js.org/en/
DATES
42
Applicazioni Web I - Web Applications I - 2021/2022
Date object
• Store a time instant with let now = new Date();
https://day.js.org/ https://moment.github.io/luxon/
https://day.js.org/docs/en/parse/parse
46
Applicazioni Web I - Web Applications I - 2021/2022
Get/Set date/time components
# obj.unit() -> get
# obj.unit(new_val) -> set
https://day.js.org/docs/en/get-set/get-set
47
Applicazioni Web I - Web Applications I - 2021/2022
Date Manipulation and Comparison
let wow = dayjs('2019-01-25').add(1, 'day').subtract(1, 'year').year(2009).toString() ;
// "Sun, 25 Jan 2009 23:00:00 GMT"
48
Applicazioni Web I - Web Applications I - 2021/2022
Day.js Plugins
• To keep install size minimal, const isLeapYear =
require('dayjs/plugin/isLeapYear’) ;
several functions are only // load plugin
– Loaded console.log(now.isLeapYear()) ;
– Registered into the libraries // use function
49
Applicazioni Web I - Web Applications I - 2021/2022
Advanced Day.js Topics
• Localization / Internationalization • Durations
– Language-aware and locale-aware – Measuring time intervals (the
parsing and formatting difference between two time
– Various formatting patterns for instants)
different locales/languages – Interval arithmetic
• Time Zones
– Conversion between time zones
50
Applicazioni Web I - Web Applications I - 2021/2022
License
• These slides are distributed under a Creative Commons license “Attribution-NonCommercial-
ShareAlike 4.0 International (CC BY-NC-SA 4.0)”
• You are free to:
– Share — copy and redistribute the material in any medium or format
– Adapt — remix, transform, and build upon the material
– The licensor cannot revoke these freedoms as long as you follow the license terms.
• Under the following terms:
– Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were
made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or
your use.
– NonCommercial — You may not use the material for commercial purposes.
– ShareAlike — If you remix, transform, or build upon the material, you must distribute your contributions
under the same license as the original.
– No additional restrictions — You may not apply legal terms or technological measures that legally restrict
others from doing anything the license permits.
• https://creativecommons.org/licenses/by-nc-sa/4.0/
51
Applicazioni Web I - Web Applications I - 2021/2022