JavaScript si è evoluto in modo straordinario a partire da ES6 (2015). Ogni anno porta nuove funzionalità che rendono il codice più conciso, leggibile e potente. Questa guida copre le funzionalità ES6+ più importanti che ogni sviluppatore dovrebbe usare quotidianamente: dalle basi come le arrow function fino alle aggiunte più recenti come l'optional chaining e la parola chiave using.
let & const (ES6)
Scope di Blocco
// const per i valori che non cambiano mai (la maggior parte delle variabili)
const API_URL = "https://api.example.com";
const users = []; // L'array è const, ma il suo contenuto può cambiare
users.push("Alice"); // ✅ Nessun problema
// let per i valori che cambiano
let count = 0;
count++;
// ❌ Non usare mai var — ha scope di funzione, non di blocco
Arrow Function (ES6)
Arrow Function
// Funzione tradizionale
function add(a, b) { return a + b; }
// Arrow function
const add = (a, b) => a + b;
// Parametro singolo — parentesi facoltative
const double = n => n * 2;
// Su più righe — servono le graffe e un return esplicito
const processUser = (user) => {
const name = user.name.trim();
return { ...user, name };
};
// Perfette per i callback
const evens = numbers.filter(n => n % 2 === 0);
const names = users.map(u => u.name);
Destructuring (ES6)
Destructuring di Oggetti e Array
// Destructuring di oggetti
const { name, email, role = "viewer" } = user;
// Rinominare le variabili
const { name: userName, email: userEmail } = user;
// Destructuring annidato
const { address: { city, country } } = user;
// Destructuring di array
const [first, second, ...rest] = [1, 2, 3, 4, 5];
// first = 1, second = 2, rest = [3, 4, 5]
// Scambiare variabili
let a = 1, b = 2;
[a, b] = [b, a]; // a = 2, b = 1
// Parametri di funzione
function greet({ name, age }) {
return `Ciao ${name}, hai ${age} anni`;
}
Operatori Spread & Rest (ES6)
Spread & Rest
// Spread — espande array/oggetti
const merged = [...arr1, ...arr2];
const copy = { ...originalObj, name: "Nuovo Nome" };
// Rest — raccoglie gli argomenti rimanenti
function sum(...numbers) {
return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4); // 10
Template Literal (ES6)
Template Literal
const name = "Alice";
const greeting = `Ciao, ${name}!`;
// Stringhe su più righe
const html = `
<div class="card">
<h2>${title}</h2>
<p>${description}</p>
</div>
`;
// Tagged template
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}<mark>${values[i] || ''}</mark>`, '');
}
Optional Chaining & Nullish Coalescing (ES2020)
?. e ??
// Optional chaining — accede in sicurezza alle proprietà annidate const city = user?.address?.city; // undefined se una qualsiasi è null/undefined const first = users?.[0]?.name; // Accesso ad array const result = user?.getProfile?.(); // Chiamata di metodo // Nullish coalescing — valore predefinito SOLO per null/undefined const port = config.port ?? 3000; // Usa 3000 solo se port è null/undefined const name = user.name ?? "Anonimo"; // Confronto con || (che intercetta anche 0, "", false) const count = data.count || 10; // ⚠️ Se count è 0, questo restituisce 10! const count = data.count ?? 10; // ✅ Restituisce 10 solo se count è null/undefined
Shorthand degli Oggetti & Proprietà Calcolate (ES6)
Miglioramenti degli Oggetti
const name = "Alice";
const age = 30;
// Shorthand delle proprietà
const user = { name, age }; // equivale a { name: name, age: age }
// Shorthand dei metodi
const api = {
async getUser(id) { /* ... */ },
async createUser(data) { /* ... */ },
};
// Nomi di proprietà calcolati
const field = "email";
const obj = { [field]: "[email protected]" };
// { email: "[email protected]" }
Moduli: import/export (ES6)
Moduli ES
// Export nominati
export const API_URL = "https://api.example.com";
export function fetchUser(id) { /* ... */ }
// Export di default
export default class UserService { /* ... */ }
// Import nominati
import { API_URL, fetchUser } from './api.js';
// Import di default
import UserService from './UserService.js';
// Rinominare all'import
import { fetchUser as getUser } from './api.js';
// Import dinamico (lazy loading)
const { Chart } = await import('./chart.js');
Funzionalità Più Recenti da Conoscere
structuredClone()(ES2022): Clona in profondità gli oggetti senza ricorrere al trucco diJSON.parse(JSON.stringify()).Array.at()(ES2022):arr.at(-1)per ottenere l'ultimo elemento.Object.groupBy()(ES2024): Raggruppa gli elementi di un array in base a una funzione chiave.awaita livello di modulo (ES2022): Usaawaitfuori dalle funzioni async nei moduli ES.
Prova i Nostri Strumenti JavaScript Gratuiti
Minifica e formatta il tuo JavaScript all'istante.