02-Le Basi
02 - Le Basi
Setup
- creare una nuova cartella e aprirla con VSCode
- creare al suo interno una nuova cartella chamata `playground
- nella cartella creare un file
index.htmle uno `playground.js - nel file
index.htmlinserire il codice
<!DOCTYPE html>
<html>
<head>
<title>Playground</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script>
<script src="./playground.js"></script>
</head>
<body>
<div class="container text-center mt-5">
<h1>Playground Page</h1>
<h3>Apri l'inspector con F12 o con click destro -> Ispeziona</h3>
<h3>Poi vai su console</h3>
</div>
</body>
</html>
Per visualizzare i risultati nel browser fare click destro sulla cartella playground e premere Open With Five Server. Se tutto va bene dovrebbe aprirsi un terminale in basso in VSCode con i log del server avviato, e dovrebbe lanciarsi automaticamente Chrome.
Per chiudere il server fare click sul fulmine giallo in basso a destra di VSCode (o chiudere il terminale).
console.log()
Stampa nella console i valori passati come argomento.
Viene molto utilizzato a scopo di debug, i browser hanno strumenti più avanzati per eseguire debug ma stampare il valore di una variabile o una scritta è più veloce per semplici controlli.
E' buona cosa togliere i console.log quando non servono più o prima di andare in produzione.
console.log("hello World");
// -> hello World
Esistono anche altri metodi di console che hanno risultati simili ma vengono usati per scopi diversi:
console.info() // non c'è differenza nel browser, ma è utile in node.js se si
// vuole impostare il log level
console.warn() // viene usato per mostrare messaggi di avvertimento, di solito
// lo si vede spesso quando si usano metodi deprecati o ci si
// dimentica di settare delle impostazioni
console.error() // mostra gli errori veri e propri, viene chiamato in automatico
// quando si verificano errori non gestiti ma può essere usato
// manualmente quando si vuole avere una traccia più precisa di
// alcuni errori
Variablili
Come in qualsiasi altro linguaggio di programmazione si usano le variabili per salvare e dare un nome riconoscibile a delle informazioni (valori numerici, stringhe, oggetti, ecc). Questo permette di utilizzarli in diversi punti del codice e manipolarli con facilità.
Dichiarazione e assegnazione
link utile
Dichiarare una variabile significa segnalarne l'esistenza, le viene dato un nome.
Ci sono 3 keyword con cui si può dichiarare una variabile:
- var è il vecchio modo usato da sempre in JavaScript. E' sconsigliato ad oggi perché è più semplice commettere errori difficili da indagare (ad esempio si possono dichiarare più variabili con lo stesso nome)
- let corregge i problemi di var ed è il modo raccomandato ad oggi
- const permette di dichiarare variabili il cui valore non può essere cambiato dopo la prima assegnazione
var firstName;
let firstName;
Nei casi qui sopra le variabili sono state dichiarate senza assegnare un valore. Una variabile senza un valore assegnato è undefined.
Per assegnare un valore a una variabile si usa l'operatore \=. Può essere fatto assieme alla dichiarazione o anche in seguito.
le variabili dichiarate con const non possono essere dichiarate senza valore.
const firstName = "Mario";
Il valore di una variabile, se non è stata creata come const, può essere riassegnato più volte.
let firstName;
firstName = "Mario";
// oppure
let firstName = "Mario";
// riassegnazione
let count = 0;
count = 1;
count = 2;
I nomi delle variabili sono case-sensitive. Possono contenere numeri (ma non può iniziare con un numero), lettere e qualsiasi carattere che non sia un operatore (ad esempio = o -).
Non ci sono regole nel formato dei nomi, per convenzione però si usa il camel case, nello specifico lowerCamelCase: prima lettera minuscola e la prima lettera di ogni successiva parola in maiuscolo.
JavaScript è un linguaggio non tipizzato, questo significa che quando viene definita una variabile può contenere qualsiasi tipo di valore e il tipo di valore può cambiare nel tempo.
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
Tipi di variabile
Primitive
Sono il tipo più basso di dato.
| Data Type | Description |
|---|---|
| String | String is a textual content wrapped inside ' ' or " " or ` ` (tick sign). Example: 'Hello World!', "This is a string", etc. |
| Number | Number is a numeric value. Example: 100, 4521983, etc. |
| Boolean | Boolean is a logical data type that has only two values, true or false. |
| Null | A null value denotes an absense of value. Example: let str = null; |
| Undefined | undefined is the default value of a variable that has not been assigned any value. Example: In the variable declaration, var str;, there is no value assigned to str. So, the type of str can be check using typeof(str) which will return undefined. |
Strutturali
Sono strutture dati che contengono altri valori primitivi o strutturali.
| Data Type | Description |
|---|---|
| Object | An object holds multiple values in terms of properties and methods. Example: js<br>let person = { <br> firstName: "James", <br> lastName: "Bond", <br> age: 15<br> }; <br> |
| Date | The Date object represents date & time including days, months, years, hours, minutes, seconds, and milliseconds. Example: let today = new Date("25 July 2021"); |
| Array | An array stores multiple values using special syntax. Example: let nums = [1, 2, 3, 4]; |
Operatori
Aritmetici
| Operator | Description |
|---|---|
| + | Adds two numeric operands. |
| - | Subtract right operand from left operand |
| * | Multiply two numeric operands. |
| / | Divide left operand by right operand. |
| % | Modulus operator. Returns remainder of two operands. |
| ++ | Increment operator. Increase operand value by one. |
| -- | Decrement operator. Decrease value by one. |
let prezzoNetto = 50;
let sconto = 30;
let prezzoScontato = prezzoNetto - (prezzoNetto * sconto / 100);
let iva = 22;
let prezzoFinale = prezzoScontato + (prezzoScontato * iva /100);
Comparazione
| Operators | Description |
|---|---|
| == | Compares the equality of two operands without considering type. |
| === | Compares equality of two operands with type. |
| != | Compares inequality of two operands. |
| > | Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false. |
| < | Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false. |
| >= | Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise, returns false. |
| <= | Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise, returns false. |
let a = 5, b = 10, c = "5";
let x = a;
a == c; // returns true
a === c; // returns false
a == x; // returns true
a != b; // returns true
a > b; // returns false
a < b; // returns true
a >= b; // returns false
a <= b; // returns true
Il numero 0, false e una stringa vuota "" sono uguali se confrontati con ==, diversi se si usa ===
let a = 0, b = '', c = false;
a == b; // true
a === b; // false
a == c; // true
a === c; // false
b == c; // true
b === c; // false