0% found this document useful (0 votes)
4 views51 pages

1 02 Javascript Objects Functions

The document provides an overview of JavaScript, focusing on objects and functions. It explains the dynamic nature of JavaScript objects, their properties, and methods, as well as various ways to declare functions, including classic, function expressions, and arrow functions. Key concepts such as property access, iteration, copying objects, and closures are also discussed.

Uploaded by

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

1 02 Javascript Objects Functions

The document provides an overview of JavaScript, focusing on objects and functions. It explains the dynamic nature of JavaScript objects, their properties, and methods, as well as various ways to declare functions, including classic, function expressions, and arrow functions. Key concepts such as property access, iteration, copying objects, and closures are also discussed.

Uploaded by

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

JavaScript: Objects

and Functions
“The” language of the Web
Fulvio Corno
Luigi De Russis
Enrico Masala

Applicazioni Web I - Web Applications I - 2021/2022


Outline
• Objects
• Functions
– Closures
• Dates

2
Applicazioni Web I - Web Applications I - 2021/2022
JavaScript: The Definitive Guide, 7th Edition
Chapter 5. Objects

Mozilla Developer Network


• Learn web development JavaScript » Dynamic client-side
scripting » Introducing JavaScript objects
• Web technology for developers » JavaScript » JavaScript
reference » Standard built-in objects » Object
• Web technology for developers » JavaScript » JavaScript
reference » Expressions and operators » in operator

JavaScript – The language of the Web

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]
};

let person = book.author;


let name = book["author"];
let numPages =
book["chapter pages"];
book.title = "Advanced JS";
book["pages"] = 340;
7
Applicazioni Web I - Web Applications I - 2021/2022
Objects as associative arrays
• The [] syntax looks like array access, but the index is a string
– Generally known as associative arrays
• Setting a non-existing property creates it:
– person["telephone"] = "0110901234";
– person.telephone = "0110901234";
• Deleting properties
– delete person.telephone;
– delete person["telephone"];

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

let surname = undefined;


if (book) {
if (book.author) {
surname = book.author.surname;
}
}

surname = book && book.author && book.author.surname;

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,
}; };

let book2 = book; // ALIAS let book3 = // COPY


Object.assign({}, book);

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,
};

let study2 = Object.assign({},


study);

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,
};

let book2 = Object.assign(


book, {title: "JS"}
);

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,
};

let book2 = Object.assign(


{}, book, {title: "JS"}
);

17
Applicazioni Web I - Web Applications I - 2021/2022
Copying with spread operator (ES9 – ES2018)

let book = { const {a,b,...others} =


author : "Enrico", {a:1, b:2, c:3, d:4};
pages: 340,
}; console.log(a);
console.log(b);
let book2 = {...book, title: "JS"}; console.log(others);
let book3 = { ...book2 } ;
console.log(book2);

{ author: 'Enrico', pages: 340, title: 'JS' } 1


2
{ c: 3, d: 4 }

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

JavaScript – The language of the Web

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

function square(x) { During


let y = x * x ; execution
return y ;
}

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

function do(params) { const fn = function(params) {


/* do something */ /* do something */
} }

2b) Named function expression

const fn = function do(params) {


/* do something */
}

27
Applicazioni Web I - Web Applications I - 2021/2022
Function expression: indistinguishable
function square(x) {
let y = x * x ;
return y ;
}

let cube = function c(x) {


let y = square(x)*x ;
return y ;
} The expression function(){} creates a new
object of type ‘function’ and returns the result.
let n = cube(4) ;
Any variable may “refer” to the function and call it.
You can also store that reference into an array, an
object property, pass it as a parameter to a function,
redefine it, …

28
method callback
Applicazioni Web I - Web Applications I - 2021/2022
Declaring functions: 3 ways
1) Classic 2a) Function expression

function do(params) { const fn = function(params) {


/* do something */ /* do something */
} }

3) Arrow function 2b) Named function expression

const fn = (params) => { const fn = function do(params) {


/* do something */ /* do something */
} }

29
Applicazioni Web I - Web Applications I - 2021/2022
Arrow Function: just a shortcut
function square(x) {
let y = x * x ;
return y ;
}

let cube = function c(x) {


let y = square(x)*x ;
return y ;
}

let fourth = (x) => { return


square(x)*square(x) ; }

let n = fourth(4) ;

30
Applicazioni Web I - Web Applications I - 2021/2022
Parameters in arrow functions
const fun = () => { /* do something */ } // no params

const fun = param => { /* do something */ } // 1 param

const fun = (param) => { /* do something */ } // 1 param

const fun = (par1, par2) => { /* smtg */ } // 2 params

const fun = (par1 = 1, par2 = 'abc') => { /* smtg */ } // default values

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) ;

• Arrow functions have implicit return if there is only one value


let fourth = (x) => { return square(x)*square(x) ; }
let fourth = x => square(x)*square(x) ;

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)

Really: one of the most


A closure is a name given to a important concepts in JS
feature in the language by which
a nested function executed after
the execution of the outer
function can still access outer
function’s scope.

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()) ;

const getNext = () => { const count2 = counter() ;


value++; console.log(count2()) ;
return value; console.log(count2()) ;
} console.log(count2()) ;

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

// return an object, d.count()


// containing two function-valued // => 0: they count independently
// properties
return { c.reset()
count: function() { // reset() and count() methods
return n++; },
c.count()
reset: function() { n = 0; }
// => 0: because we reset c
};
} d.count()
// => 1: d was not reset

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

function Car(make, model, year) {


this.make = make;
this.model = model; let mycar = new Car('Eagle',
this.year = year; 'Talon TSi', 1993);
this.isNew = ()=>(year>2000);
}

41
Applicazioni Web I - Web Applications I - 2021/2022
JavaScript: The Definitive Guide, 7th Edition
Chapter 9.4 Dates and Times

Mozilla Developer Network


Web technology for developers » JavaScript »
JavaScript reference »
Standard built-in objects » Date

Day.js
https://day.js.org/en/

JavaScript – The language of the Web

DATES

42
Applicazioni Web I - Web Applications I - 2021/2022
Date object
• Store a time instant with let now = new Date();

millisecond precision, counted from


Jan 1, 1970 UTC (Unix Epoch)
• Careful with time zones let newYearMorning = new Date(
– Most methods work in local time (not 2021, // Year 2021
UTC) the computer is set to 0, // January (from 0)
1, // 1st
18, 15, 10, 743);
UTC vs Local time zone are confusing. // 18:15:10.743, local time
> new Date('2020-03-18')
2020-03-18T00:00:00.000Z Comparisons are difficult (no way
Formatting is locale-
> new Date('18 March 2020') to specify which fields you want,
dependent
2020-03-17T23:00:00.000Z must set them to zero explicitly)
😱😱
😱 😱😱😱
43
Applicazioni Web I - Web Applications I - 2021/2022
Serious JS date/time handling libraries

https://day.js.org/ https://moment.github.io/luxon/

https://momentjs.com/ https://date-fns.org/ https://js-joda.github.io/js-joda/


44
Applicazioni Web I - Web Applications I - 2021/2022
https://day.js.org/
Day.js Library
• Goals • Install
– Compatible with moment.js npm init # if not already done
• But very small (2kB) npm install dayjs
– Works in nodejs and in the browser • Import
– All objects are immutable const dayjs = require('dayjs')
• All API functions that modify a date,
will always return a new object • Use
instance let now = dayjs()
– Localization console.log(now.format())
– Plugin system for extending
functionality
45
Applicazioni Web I - Web Applications I - 2021/2022
Basic operations with Day.js
Creating date objects – dayjs() constructor Displaying date objects – format()
let now = dayjs() // today console.log(now.format());
let date1 = dayjs('2019-12-27T16:00'); 2021-03-02T16:38:38+01:00
// from ISO 8601 format
let date2 = dayjs('20191227'); console.log(now.format('YYYY-MM [on the] DD'));
// from 8-digit format 2021-03 on the 02
let date3 = dayjs(new Date(2019, 11, 27));
// from JS Date object console.log(now.toString());
let date5 = dayjs.unix(1530471537); Tue, 02 Mar 2021 15:43:46 GMT
// from Unix timestamp
By default, Day.js displays in local time
By default, Day.js parses in local time

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

let now2 = now.date(15);


let now2 = now.set('date', 15);
2021-03-15T16:50:26+01:00

let now3 = now.minute(45);


let now3 = now.set('minute',45);
2021-03-02T16:45:26+01:00

let today_day = now.day();


let today_day = now.get('day');
2

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"

• Methods to "modify" a date (and • Day.js objects can be compared


return a modified one) • .isBefore / .isSame /
• .add / .subtract .isAfter
• .startOf / .endOf • .isBetween
• d1.diff(d2, ‘unit’) • .isLeapYear / .daysInMonth
• Specify the unit to be
added/subtracted/rounded
• Can be easily chained

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

available in plugins dayjs.extend(isLeapYear) ;


• Plugins must be // register plugin

– Loaded console.log(now.isLeapYear()) ;
– Registered into the libraries // use function

• Then, functions may be freely


used

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

You might also like