1 01 Javascript Basics
1 01 Javascript Basics
3
Applicazioni Web I - Web Applications I - 2023/2024
Outline
• What is JavaScript?
• History and versions
• Language structure
• Types, variables
• Expressions
• Control structures
• Arrays
• Strings
4
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript – The language of the Web
WHAT IS JAVASCRIPT?
5
Applicazioni Web I - Web Applications I - 2023/2024
source: https://octoverse.github.com/#top-languages
6
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript
• JavaScript (JS) is a programming language
• It is currently the only programming language that a browser can
execute natively…
• … and it also run on a computer, like other programming languages
(thanks to Node.js)
• It has nothing to do with Java
– named that way for marketing reasons, only
• The first version was written in 10 days (!)
– several fundamental language decisions were made because of company politics
and not technical reasons!
7
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript – The language of the Web
8
Applicazioni Web I - Web Applications I - 2023/2024
Brendan Eich
https://www.ecma-international.org/ecma-262/
10
yrs
Main
Also: ES2015
target
Also: ES2016
ES9,
Also: ES2017
ES10,
9
…
Applicazioni Web I - Web Applications I - 2023/2024
https://www.slideshare.net/RafaelCasusoRomate/javascript-editions-es7-es8-and-es9-vs-v8
JavaScript versions
• ECMAScript (also called ES) is the official name of JavaScript (JS) standard
• ES6, ES2015, ES2016 etc. are implementations of the standard
• All browsers used to run ECMAScript 3
• ES5, and ES2015 (=ES6) were huge versions of JavaScript
• Then, yearly release cycles started
– By the committee behind JS: TC39, backed by Mozilla, Google, Facebook, Apple,
Microsoft, Intel, PayPal, SalesForce, etc.
• ES2015 (=ES6) is covered in this course
10
Applicazioni Web I - Web Applications I - 2023/2024
Official ECMA standard (formal and unreadable)
https://www.ecma-international.org/ecma-262/
11
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript Engines
• V8 (Chrome V8) by Google
– used in Chrome/Chromium, Node.js and Microsoft Edge
• SpiderMonkey by Mozilla Foundation
– Used in Firefox/Gecko
• ChakraCore by Microsoft
– it was used in Edge
• JavaScriptCore by Apple
– used in Safari
12
Applicazioni Web I - Web Applications I - 2023/2024
Standard vs. Implementation (in browsers)
13
Applicazioni Web I - Web Applications I - 2023/2024
JS Compatibility
• JS is backwards-compatible
– once something is accepted as valid JS, there will not be a future change to the language
that causes that code to become invalid JS
– TC39 members: "we don't break the web!"
• JS is not forwards-compatible
– new additions to the language will not run in an older JS engine and may crash the
program
• strict mode was introduced to disable very old (and dangerous) semantics
• Supporting multiple versions is achieved by:
– Transpiling – Babel (https://babeljs.io) converts from newer JS syntax to an equivalent
older syntax
– Polyfilling – user- (or library-)defined functions and methods that “fill” the lack of a
feature by implementing the newest available one
14
Applicazioni Web I - Web Applications I - 2023/2024
JS Execution Environments https://nodejs.org/en/download/package-
Linux/Unix manager/
https://nodejs.org/
Server & CLI https://docs.microsoft.com/en-
Windows Native us/windows/nodejs/setup-on-windows
Node.js
Runtime
JS (ES6)
Browser
Developer tools
http://pythontutor.com/javascript.html
JavaScriptTutor
Understanding
https://jsconsole.com/
jsconsole
15
Applicazioni Web I - Web Applications I - 2023/2024
JavaScriptTutor
http://pythontutor.com/javascript.html
16
Applicazioni Web I - Web Applications I - 2023/2024
Browser and JS console
17
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript – The language of the Web
LANGUAGE STRUCTURE
18
Applicazioni Web I - Web Applications I - 2023/2024
Lexical structure
• One File = One JS program
– Each file is loaded independently and
– Different files/programs may communicate through global state
– The “module” mechanism extends that (provides state sharing in a clean way)
• The file is entirely parsed, and then executed from top to bottom
• Relies on a standard library
– and many additional APIs provided by the execution environment
19
Applicazioni Web I - Web Applications I - 2023/2024
> let ööö = 'appalled'
Lexical structure
> ööö
'appalled'
20
Applicazioni Web I - Web Applications I - 2023/2024
Semicolon (;)
• Argument of debate in the JS community
• JS inserts them as needed
– When next line starts with code that breaks the current one
– When the next line starts with }
– When there is return, break, throw, continue on its own line
• Be careful that forgetting semicolon can lead to unexpected behavior
– A newline does not automatically insert a semicolon: if the next line starts with ( or [ , it
is interpreted as function call or array access
• We will loosely follow the Google style guide, so we will always insert
semicolons after each statement
– https://google.github.io/styleguide/jsguide.html
21
Applicazioni Web I - Web Applications I - 2023/2024
// first line of file
Strict Mode
"use strict" ;
// always!!
22
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 2. Types, Values, and Variables
23
Applicazioni Web I - Web Applications I - 2023/2024
Values and Types Values have types.
Variables don’t.
Value
Primitive Object
User-
'abc' 3.1415 false
defined
`abc`
24
Applicazioni Web I - Web Applications I - 2023/2024
Boolean, true-truthy, false-falsy, comparisons
• ‘boolean’ type with literal values: true, false
• When converting to boolean
> Boolean(3)
– The following values are ‘falsy’ true
• 0, -0, NaN, undefined, null, '' (empty string) > Boolean('')
false
– Every other value is ‘truthy’ > Boolean(' ')
• 3, 'false', [] (empty array), {} (empty object) true
25
Applicazioni Web I - Web Applications I - 2023/2024
Number
• No distinction between integers and reals
• Automatic conversions according to the operation
26
Applicazioni Web I - Web Applications I - 2023/2024
Special values
• undefined: variable declared but not initialized
– Detect with: typeof variable === 'undefined'
– void x always returns undefined
• null: an empty value
• Null and Undefined are called nullish values
• The same variable may refer to different values (even of different types)
at different times
> let a = 5
> const b = 6
• Declaring a variable: > var c = 7
> a = 8
– let 8
> b = 9
– const Thrown:
– var TypeError: Assignment to
constant variable.
> c = 10
10
28
Applicazioni Web I - Web Applications I - 2023/2024
Variable declarations
Declarator Can reassign? Can re-declare? Scope Hoisting * Note
let Yes No Enclosing block No Preferred
{…}
const No § No Enclosing block No Preferred
{…}
var Yes Yes Enclosing Yes, to beginning Legacy, beware
function, of function or file its quirks, try not
or global to use
None (implicit) Yes N/A Global Yes Forbidden in
strict mode
let a = 1 ;
const b = 2 ;
let c = true ;
30
Applicazioni Web I - Web Applications I - 2023/2024
Scope Typically, you don't
create a new scope in
this way!
"use strict" ;
let a = 1 ;
const b = 2 ;
let c = true ;
console.log(a) ;
31
Applicazioni Web I - Web Applications I - 2023/2024
Scope and Hoisting
"use strict" ;
console.log(a) ; // 1
console.log(b) ; // ReferenceError: b is not defined
console.log(c) ; // undefined
if( x>1 ) {
let b = a+1 ;
var c = a*2 ;
}
console.log(a) ; // 1
console.log(b) ; // ReferenceError: b is not defined
console.log(c) ; // 2
}
example(2) ;
32
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 2. Types, Values, and Variables
Chapter 3. Expressions and Operators
EXPRESSIONS
33
Applicazioni Web I - Web Applications I - 2023/2024
Operators
• Assignment operators
• Comparison operators
• Arithmetic operators
• Bitwise operators Full reference and operator precedence:
https://developer.mozilla.org/en-
• Logical operators US/docs/Web/JavaScript/Reference/Operators/Oper
ator_Precedence#Table
• String operators
• Conditional (ternary) operator
• Comma operator
• Unary operators
• Relational operators
34
Applicazioni Web I - Web Applications I - 2023/2024
Assignment
• let variable = expression ; // declaration with initialization
• variable = expression ; // reassignment
35
Applicazioni Web I - Web Applications I - 2023/2024
Comparison operators
36
Applicazioni Web I - Web Applications I - 2023/2024
Comparing Objects
• Comparison between objects with == or ===
> a={x:1}
compares the references to objects { x: 1 }
– True only if they are the same object > b={x:1}
– False if they are identical objects { x: 1 }
• Comparison with < > <= >= first converts the object > a===b
(into a Number, or more likely a String), and then false
37
Applicazioni Web I - Web Applications I - 2023/2024
Automatic Type Conversions
Number(b)
true -> 1
• JS tries to apply type conversions truthy-falsy rule
Boolean(a)
Boolean false -> 0
https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch4.md
38
Applicazioni Web I - Web Applications I - 2023/2024
Logical operators
39
Applicazioni Web I - Web Applications I - 2023/2024
Common operators
40
Applicazioni Web I - Web Applications I - 2023/2024
Mathematical functions (Math global object)
• Constants: Math.E, Math.LN10, Math.LN2, Math.LOG10E,
Math.LOG2E, Math.PI, Math.SQRT1_2, Math.SQRT2
• Functions: Math.abs(), Math.acos(), Math.acosh(),
Math.asin(), Math.asinh(), Math.atan(), Math.atan2(),
Math.atanh(), Math.cbrt(), Math.ceil(), Math.clz32(),
Math.cos(), Math.cosh(), Math.exp(), Math.expm1(),
Math.floor(), Math.fround(), Math.hypot(), Math.imul(),
Math.log(), Math.log10(), Math.log1p(), Math.log2(),
Math.max(), Math.min(), Math.pow(), Math.random(),
Math.round(), Math.sign(), Math.sin(), Math.sinh(),
Math.sqrt(), Math.tan(), Math.tanh(), Math.trunc()
41
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 4. Statements
CONTROL STRUCTURES
42
Applicazioni Web I - Web Applications I - 2023/2024
Conditional statements May also be a string
43
Applicazioni Web I - Web Applications I - 2023/2024
Loop statements
for ([initialExpression]; [condition]; [incrementExpression]) {
statement ;
}
Usually declares loop
variable
while (condition) {
statement ;
}
44
Applicazioni Web I - Web Applications I - 2023/2024
Preferred
• Iterates the variable over all the • Iterates the variable over all values of
enumerable properties of an object an iterable object (including Array,
• Do not use to traverse an array (use Map, Set, string, arguments …)
numerical indexes, or for-of) • Returns the values, not the keys
for( let a in {x: 0, y:3}) { for( let a of [4,7]) { for( let a of "hi" ) {
console.log(a) ; console.log(a) ; console.log(a) ;
} } }
x 4 h
y 7 i
45
Applicazioni Web I - Web Applications I - 2023/2024
Other iteration methods
• Functional programming (strongly supported by JS) allows other
methods to iterate over a collection (or any iterable object)
– a.forEach()
– a.map()
• They will be analyzed later
46
Applicazioni Web I - Web Applications I - 2023/2024
Exception handling
try { throw object ;
statements ;
} catch(e) {
statements ; EvalError
} Exception object RangeError
ReferenceError
try { SyntaxError
statements ; TypeError
} catch(e) { URIError
statements ; DOMException
} finally { Contain fields: name,
statements ; message
}
Executed in any case, at
the end of try and catch
blocks
47
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 6. Arrays
ARRAYS
48
Applicazioni Web I - Web Applications I - 2023/2024
Arrays
• Rich of functionalities
• Elements do not need to be of the same type
• Simplest syntax: []
• Property .length
• Distinguish between methods that:
– Modify the array (in-place)
– Return a new array
49
Applicazioni Web I - Web Applications I - 2023/2024
Elements are indexed at
Creating an array positions 0...length-1
Do not access elements
outside range
let v = [] ;
50
Applicazioni Web I - Web Applications I - 2023/2024
Adding elements
.lenght adjusts
automatically
let v = [] ; let v = [] ;
v[0] = "a" ; v.push("a") ;
v[1] = 8 ; v.push(8) ;
v.length // 2 v.length // 2
.unshift() adds at
the beginning of the
array
51
Applicazioni Web I - Web Applications I - 2023/2024
Adding and Removing from arrays (in-place)
v.unshift(x) v.push(x)
x = v.shift() x = v.pop()
52
Applicazioni Web I - Web Applications I - 2023/2024
Copying arrays
let v = [] ;
v[0] = "a" ; ?
v[1] = 8 ;
let alias = v ;
alias[1] = 5 ;
53
Applicazioni Web I - Web Applications I - 2023/2024
Copying arrays
let v = [] ;
v[0] = "a" ;
v[1] = 8 ;
let alias = v ;
let copy = Array.from(v) ;
Array.from creates a
shallow copy
56
Applicazioni Web I - Web Applications I - 2023/2024
Destructuring assignment
• Value of the right-hand side of equal signal are extracted and stored in the
variables on the left
57
Applicazioni Web I - Web Applications I - 2023/2024
Spread operator (3 dots:...)
• Expands an interable object in its parts, when the syntax requires a
comma-separated list of elements
let [x, ...y] = [1,2,3,4]; // we obtain y == [2,3,4]
58
Applicazioni Web I - Web Applications I - 2023/2024
Curiosity
• Copy by value:
– const b = Array.from(a)
• Can be emulated by
– const b = Array.of(...a)
– const b = [...a]
Frequent
idiom
59
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 2. Types, Values, and Variables
STRINGS
60
Applicazioni Web I - Web Applications I - 2023/2024
Strings in JS
• A string is an immutable ordered sequence of Unicode(*) characters
• The length of a string is the number of characters it contains (not bytes)
• JavaScript’s strings use zero-based indexing
– The empty string is the string of length 0
• JavaScript does not have a special type that represents a single character
(use length-1 strings).
• String literals may be defined with 'abc' or "abc"
– Note: when dealing with JSON parsing, only " " can be correctly parsed
61
Applicazioni Web I - Web Applications I - 2023/2024
String operations
• All operations always return new strings
– Consequence of immutability
• s[3]: indexing
• s1 + s2: concatenation
• s.length: number of characters
– Note: .length , not .length()
62
Applicazioni Web I - Web Applications I - 2023/2024
String
methods
63
Applicazioni Web I - Web Applications I - 2023/2024
Unicode issues
• Strings are a sequence of 16-bit Unicode ‘code units’
– Fine for all Unicode characters from 0000 to FFFF
– Characters (‘graphemes’) from 010000 to 10FFFF are represented by a pair of
code units (and they occupy 2 index positions)
– Therefore, not all string methods work well with Unicode characters above FFFF
(e.g., emojis, flags, …)
64
Applicazioni Web I - Web Applications I - 2023/2024
Template literals
• Strings included in `backticks` can embed expressions delimited by ${}
• The value of the expression is interpolated into the string
let name = "Bill";
let greeting = `Hello ${ name }.`;
// greeting == "Hello Bill."
• Very useful and quick for string formatting
• Template literals may also span multiple lines
65
Applicazioni Web I - Web Applications I - 2023/2024
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/
66
Applicazioni Web I - Web Applications I - 2023/2024