0% found this document useful (0 votes)
5K views

1 01 Javascript Basics

Uploaded by

digidev.sarl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5K views

1 01 Javascript Basics

Uploaded by

digidev.sarl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

JavaScript (basics)

“The” language of the Web


Fulvio Corno
Luigi De Russis

Applicazioni Web I - Web Applications I - 2023/2024


https://www.codemio.com/2016/09/html5-css3-javascript-cheat-sheets.html 2
Applicazioni Web I - Web Applications I - 2023/2024
Goal
• Learn JavaScript as a language
• Understand the specific semantics and programming patterns
– We assume a programming knowledge in other languages
• Updated to ES6 (2015) language features
• Supported by server-side (Node.js) and client-side (browsers) run-time
environments
– More recent language additions also supported (through transpiling)

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

HISTORY AND VERSIONS

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

WSL2 under https://docs.microsoft.com/en-


Windows us/windows/nodejs/setup-on-wsl2

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'

• JavaScript is written in Unicode (do not abuse), so it also supports non-


latin characters for names and strings
– even emoji
• Semicolons (;) are not mandatory (automatically inserted)
• Case sensitive
• Comments as in C (/*..*/ and // )
• Literals and identifiers (start with letter, $, _)
• Some reserved words
• C-like syntax

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!!

• Directive introduced in ES5: "use strict" ;


– Compatible with older version (it is just a string)
• Code is executed in strict mode
– This fixes some important language deficiencies and provides stronger error checking and
security
– Examples:
• fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode
code can sometimes be made to run faster than identical code that's not strict mode
• eliminates some JavaScript silent errors by changing them to throw errors
• functions invoked as functions and not as methods of an object have this undefined
• cannot define 2 or more properties or function parameters with the same name
• no octal literals (base 8, starting with 0)
• ...

22
Applicazioni Web I - Web Applications I - 2023/2024
JavaScript: The Definitive Guide, 7th Edition
Chapter 2. Types, Values, and Variables

JavaScript – The language of the Web

TYPES AND VARIABLES

23
Applicazioni Web I - Web Applications I - 2023/2024
Values and Types Values have types.
Variables don’t.

Value

Primitive Object

string number boolean null undefined Array

"abc" 42 true Function

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

• Booleans and Comparisons


– a == b // convert types and compare results
– a === b // inhibit automatic type conversion and compare results

25
Applicazioni Web I - Web Applications I - 2023/2024
Number
• No distinction between integers and reals
• Automatic conversions according to the operation

• There is also a distinct type "BigInt" (ES11, July 2020)


– an arbitrary-precision integer, can represent 253 numbers
– 123456789n
– With suffix ‘n’

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

• NaN (Not a Number)


– It is actually a number
– Invalid output from arithmetic operation or parse operation
27
Applicazioni Web I - Web Applications I - 2023/2024
Variables > v = 7 ;
7
> v = 'hi' ;
• Variables are pure references: they refer to a value 'hi'

• 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

* Hoisting = “lifting up” the definition of a variable (not


§Prevents reassignment (a=2), does not prevent
the initialization!) to the top of the current scope (e.g.,
changing the value of the referred object (a.b=2)
the file or the function)
29
Applicazioni Web I - Web Applications I - 2023/2024
Scope
"use strict" ;

let a = 1 ;
const b = 2 ;
let c = true ;

let a = 5 ; // SyntaxError: Identifier 'a' has already been declared

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 ;

{ // creating a new scope...


let a = 5 ;
console.log(a) ;
}

console.log(a) ;

Each { } is called a block. 'let' and 'const' variables are block-scoped.

They exist only in their defined and inner scopes.

31
Applicazioni Web I - Web Applications I - 2023/2024
Scope and Hoisting
"use strict" ;

function example(x) { var c ; // hoisted


let a = 1 ;

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

Mozilla Developer Network


JavaScript Guide » Expressions and operators

JavaScript – The language of the Web

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

compares the values > a==b


false
– It works, but may be unpredictable, depending on the
string format

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

between primitive types, before !!a

applying operators Any type Number(s)


+s

• Some language constructs may a.toString()


s-0
parseInt(s)

be used to “force” the desired


parseFloat(s)
String(a)

conversions String Number


n.toString()

• Using == applies conversions String(n)


n+""

• Using === prevents conversions

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

Or string Useful idiom:


concatenation a||b
if a then a else b
(a, with default b)

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

Mozilla Developer Network


JavaScript Guide » Control Flow and Error Handling
JavaScript Guide » Loops and Iteration

JavaScript – The language of the Web

CONTROL STRUCTURES

42
Applicazioni Web I - Web Applications I - 2023/2024
Conditional statements May also be a string

if (condition) { switch (expression) {


statement_1; if truthy (beware!) case label_1:
} else { statements_1
statement_2; [break;]
} case label_2:
statements_2
if (condition_1) { [break;]
statement_1; …
} else if (condition_2) { default:
statement_2; statements_def
} else if (condition_n) { [break;]
statement_n; }
} else {
statement_last;
}

43
Applicazioni Web I - Web Applications I - 2023/2024
Loop statements
for ([initialExpression]; [condition]; [incrementExpression]) {
statement ;
}
Usually declares loop
variable

May use break; or


do { continue;
statement ;
} while (condition);

while (condition) {
statement ;
}

44
Applicazioni Web I - Web Applications I - 2023/2024
Preferred

Special ‘for’ statements


for (variable in object) { for (variable of iterable) {
statement ; statement ;
} }

• 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

Mozilla Developer Network


JavaScript Guide » Indexed Collections

JavaScript – The language of the Web

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 = [] ;

let v = [1, 2, 3] ; let v = Array.of(1, 2, 3) ;

let v = [1, "hi", 3.1, true]; let v = Array.of(1, "hi",


3.1, true) ;

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

.push() adds at the


end of the array

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

[0] [1] [2] [3] … … [n-1]

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

Creates an array from


any iterable object
54
Applicazioni Web I - Web Applications I - 2023/2024
Iterating over Arrays
Preferred

• Iterators: for ... of, for (..;..;..)


• Iterators: forEach(f)
– f is a function that processes the element
Functional style – later

• Iterators: every(f), some(f)


– f is a function that returns true or false
• Iterators that return a new array: map(f), filter(f)
– f works on the element of the array passed as parameter
• Reduce: exec a callback function on all items to progressively compute a
result
55
Applicazioni Web I - Web Applications I - 2023/2024
Main array methods
• .concat() • .reverse()
– joins two or more arrays and returns a new – transposes the elements of an array, in place
array. • .sort()
• .join(delimiter = ',') – sorts the elements of an array in place
– joins all elements of an array into a (new) • .indexOf(searchElement[,
string.
fromIndex])
• .slice(start_index, upto_index) – searches the array for searchElement and
– extracts a section of an array and returns a returns the index of the first match
new array.
• .lastIndexOf(searchElement[,
• .splice(index, count_to_remove, fromIndex])
addElement1, addElement2, ...) – like indexOf, but starts at the end
– removes elements from an array and
(optionally) replaces them, in place • .includes(valueToFind[,
fromIndex])
– search for a certain value among its entries,
returning true or false

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

let [x,y] = [1,2];


[x,y] = [y,x]; // swap

var foo = ['one', 'two', 'three'];


var [one, two, three] = foo;

• Useful especially with passing and returning values from functions

let [x,y] = toCartesian(r,theta);

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]

const parts = ['shoulders', 'knees'];


const lyrics = ['head', ...parts, 'and', 'toes']; // ["head", "shoulders",
"knees", "and", "toes"]

• Works on the left- and right-hand side of the assignment

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

Mozilla Developer Network


JavaScript Guide » Text Formatting

JavaScript – The language of the Web

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, …)

• For more details: https://dmitripavlutin.com/what-every-javascript-


developer-should-know-about-unicode/

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

You might also like