Basi
Variabili
let name = "Alice"; // reassignable const PI = 3.14; // constant var old = "avoid"; // function-scoped (legacy)
Tipi di Dato
stringTesto: "hello" o 'hello'
numberIntero o float: 42, 3.14
booleantrue / false
nullValore vuoto intenzionale
undefinedDichiarato ma non assegnato
objectCoppie chiave-valore: { a: 1 }
arrayLista ordinata: [1, 2, 3]
symbolIdentificatore unico
Controllo e Conversione del Tipo
typeof "hello" // "string" typeof 42 // "number" Number("42") // 42 String(100) // "100" parseInt("3.9") // 3 parseFloat("3.14") // 3.14
Stringhe
Template Literal
const name = "Alice"; `Hello, ${name}!` // Hello, Alice! `Total: ${2 + 3}` // Total: 5 `Multi line string`
Metodi delle Stringhe
s.lengthNumero di caratteri
s.toUpperCase()Copia in MAIUSCOLO
s.toLowerCase()Copia in minuscolo
s.trim()Rimuove spazi iniziali/finali
s.split(",")Divide in array
s.includes("x")Verifica presenza → bool
s.indexOf("x")Primo indice (-1 se assente)
s.slice(1, 4)Sottostringa per indice
s.replace(a, b)Sostituisce prima occorrenza
s.replaceAll(a, b)Sostituisce tutte le occorrenze
s.startsWith(x)Controlla prefisso → bool
s.endsWith(x)Controlla suffisso → bool
s.padStart(n, c)Riempie l'inizio fino alla lunghezza n
Array
Creare e Accedere
const fruits = ["apple", "banana", "cherry"]; fruits[0] // "apple" fruits.length // 3 fruits.at(-1) // "cherry"
Metodi Mutanti
arr.push(x)Aggiunge in fondo
arr.pop()Rimuove e restituisce l'ultimo
arr.unshift(x)Aggiunge in testa
arr.shift()Rimuove e restituisce il primo
arr.splice(i, n)Rimuove n elementi all'indice i
arr.sort()Ordina in-place (lessicografico)
arr.reverse()Inverte in-place
Metodi Non Mutanti
arr.map(fn)Trasforma ogni elemento
arr.filter(fn)Mantiene gli elementi dove fn è true
arr.reduce(fn, init)Accumula in un singolo valore
arr.find(fn)Prima corrispondenza o undefined
arr.findIndex(fn)Indice della prima corrispondenza (-1)
arr.includes(x)Verifica presenza → bool
arr.slice(a, b)Copia superficiale di una porzione
arr.join(",")Unisce in stringa
arr.forEach(fn)Itera (nessun valore di ritorno)
[...a, ...b]Concatena array (spread)
Oggetti
Creare e Accedere
const user = { name: "Alice", age: 20 }; user.name // "Alice" user["age"] // 20 user.gpa = 3.85; // add/update
Destrutturazione e Spread
const { name, age } = user; const copy = { ...user, age: 21 };
Metodi degli Oggetti
Object.keys(o)Array di chiavi
Object.values(o)Array di valori
Object.entries(o)Array di coppie [chiave, valore]
Object.assign(t, s)Copia proprietà da s a t
"k" in objLa chiave esiste? → bool
delete obj.kRimuove proprietà
Object.freeze(o)Rende immutabile (shallow)
Controllo del Flusso
if / else if / else
if (score >= 90) { grade = "A"; } else if (score >= 80) { grade = "B"; } else { grade = "C"; }
Ternario e Nullish Coalescing
const status = score >= 60 ? "pass" : "fail"; const name = user.name ?? "Anonymous";
switch
switch (color) { case "red": stop(); break; case "green": go(); break; default: wait(); }
Cicli
for / for...of / for...in
for (let i = 0; i < 5; i++) { } for (const item of ["a", "b"]) { } // arrays for (const key in obj) { } // object keys
while / do...while
while (count < 10) { count++; } do { count++; } while (count < 10);
break e continue
for (let i = 0; i < 10; i++) { if (i === 5) break; // stop loop if (i % 2 === 0) continue; // skip }
Funzioni
Dichiarazione e Arrow Function
function greet(name) { return `Hello, ${name}!`; } const greet = (name) => `Hello, ${name}!`; const square = x => x * x; // single param
Parametri Default e Rest
function greet(name = "World") { } function sum(...nums) { return nums.reduce((a, b) => a + b, 0); }
Callback
[1, 2, 3].map(x => x * 2); // [2, 4, 6] [1, 2, 3].filter(x => x > 1); // [2, 3] setTimeout(() => console.log("done"), 1000);
Classi
class Dog { constructor(name, breed) { this.name = name; this.breed = breed; } bark() { return `${this.name} says Woof!`; } } class Puppy extends Dog { constructor(name, breed, toy) { super(name, breed); this.toy = toy; } }
Gestione degli Errori
try { JSON.parse("bad json"); } catch (err) { console.error(err.message); } finally { console.log("always runs"); }
Lanciare Errori
throw new Error("Something went wrong");
DOM
Selezionare Elementi
document.querySelector(".cls") // first match document.querySelectorAll("li") // all matches document.getElementById("main")
Modificare Elementi
el.textContent = "new text"; el.innerHTML = "bold"; el.style.color = "red"; el.classList.add("active"); el.classList.toggle("hidden"); el.setAttribute("data-id", "42");
Eventi
btn.addEventListener("click", (e) => { console.log(e.target); });
Creare Elementi
const li = document.createElement("li"); li.textContent = "New item"; ul.appendChild(li); el.remove(); // remove element
Fetch API
Richiesta GET
fetch("https://api.example.com/data") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err));
Richiesta POST
fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ key: "value" }), });
Async / Await
async function loadData() { try { const res = await fetch(url); const data = await res.json(); return data; } catch (err) { console.error(err); } }
Richieste Parallele
const [users, posts] = await Promise.all([ fetch("/users").then(r => r.json()), fetch("/posts").then(r => r.json()), ]);
Moduli
Export Nominali
// math.js export const PI = 3.14; export function add(a, b) { return a + b; } // main.js import { PI, add } from "./math.js";
Export Default
// logger.js export default function log(msg) { } // main.js import log from "./logger.js";