Questa pagina non è disponibile in tutte le lingue. Le traduzioni mancanti sono disabilitate nel selettore.

Riferimento rapido

Guida rapida a JavaScript ES2015+

Esempi di sintassi e riferimenti per JavaScript da ES2015.

· Pubblicato · Aggiornato

La guida copre ES2015, ES2016, ES2017, ES2018 e versioni successive. Gli esempi sono indipendenti e i puntini indicano codice applicativo omesso.

Ambito di blocco

Let

function fn () {
  let x = 0
  if (true) {
    let x = 1 // only inside this `if`
  }
}

Const

const a = 1

let e const hanno ambito di blocco, var di funzione. const impedisce la riassegnazione ma non congela gli oggetti. let and const

Letterali modello

Interpolazione

const message = `Hello ${name}`

Stringhe multilinea

const str = `
hello
world
`

I modelli supportano interpolazione e testo multilinea. Template strings

Letterali binari e ottali

let bin = 0b1010010
let oct = 0o755

Binary and octal literals

Nuovi metodi

Metodi delle stringhe

"hello".repeat(3)
"hello".includes("ll")
"hello".startsWith("he")
"hello".padStart(8) // "   hello"
"hello".padEnd(8) // "hello   "
"hello".padEnd(8, '!') // hello!!!
"\u1E9B\u0323".normalize("NFC")

New methods

Classi

class Shape {
  constructor (radius) { this.radius = radius }
  expand (n) { return this.radius * n }
}
class Circle extends Shape {

Costruttore

  constructor (radius) {
    super(radius)
    this.radius = radius
  }

Metodi

  getArea () {
    return Math.PI * this.radius ** 2
  }

Chiamare un metodo della superclasse

  expand (n) {
    this.radius = super.expand(n)
    return this
  }

Metodi statici

  static createFromDiameter(diameter) {
    return new Circle(diameter / 2)
  }
}

La sintassi delle classi si basa sui prototipi. Questi frammenti formano un solo esempio. Il costruttore derivato chiama super prima di accedere a this. Classes

Elevamento a potenza

const byte = 2 ** 8
// Same as: Math.pow(2, 8)

Promesse

Creare una promessa

new Promise((resolve, reject) => {
  if (ok) { resolve(result) }
  else { reject(error) }
})

Le promesse rappresentano il completamento o il fallimento di operazioni asincrone. Promises

Usare una promessa

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })

Usare finally

promise
  .then((result) => { ··· })
  .catch((error) => { ··· })
  .finally(() => { /* logic independent of success/error */ })

Il gestore di successo riceve il risultato, quello di rifiuto riceve l’errore. finally viene eseguito dopo il completamento senza ricevere tali valori.

Utilità per le promesse

Promise.all(···)
Promise.race(···)
Promise.reject(···)
Promise.resolve(···)

async / await

async function run () {
  const user = await getUser()
  const tweets = await getTweets(user)
  return [user, tweets]
}

Una funzione async restituisce una promessa. await sospende la funzione fino al completamento del suo operando.

Async functions

Destrutturazione

Assegnazione per destrutturazione

Array

const [first, last] = ['Nikola', 'Tesla']

Oggetti

let {title, author} = {
  title: 'The Silkworm',
  author: 'R. Galbraith'
}

La destrutturazione estrae valori dagli array e proprietà dagli oggetti. Destructuring

Valori predefiniti

const scores = [22, 33]
const [math = 50, sci = 50, arts = 50] = scores
// Result:
// math === 22, sci === 33, arts === 50

I valori predefiniti valgono per undefined, non per null.

Parametri di funzione

function greet({ name, greeting }) {
  console.log(`${greeting}, ${name}!`)
}
greet({ name: 'Larry', greeting: 'Ahoy' })

I parametri possono destrutturare array e oggetti.

Valori predefiniti

function greet({ name = 'Rauno' } = {}) {
  console.log(`Hi ${name}!`);
}
greet() // Hi Rauno!
greet({ name: 'Larry' }) // Hi Larry!

Rinominare proprietà

function printCoordinates({ left: x, top: y }) {
  console.log(`x: ${x}, y: ${y}`)
}
printCoordinates({ left: 25, top: 90 })

left viene assegnato alla variabile locale x e top a y.

Cicli

for (let {title, artist} of songs) {
  ···
}

La destrutturazione funziona anche nelle dichiarazioni dei cicli.

Destrutturare oggetti

const { id, ...detail } = song;

La sintassi rest raccoglie le proprietà proprie enumerabili rimanenti.

Espansione

Espansione di oggetti

Con espansione di oggetti

const options = {
  ...defaults,
  visible: true
}

Senza espansione di oggetti

const options = Object.assign(
  {}, defaults,
  { visible: true })

L’espansione di oggetti copia superficialmente le proprietà proprie enumerabili. Quelle successive sovrascrivono le precedenti.

Object spread

Espansione di array

Con espansione di array

const users = [
  ...admins,
  ...editors,
  'rstacruz'
]

Senza espansione di array

const users = admins
  .concat(editors)
  .concat([ 'rstacruz' ])

L’espansione crea un nuovo array dai valori di un iterabile.

Spread syntax

Funzioni

Parametri di funzione

Parametri predefiniti

function greet (name = 'Jerry') {
  return `Hello ${name}`
}

Parametri rest

function fn(x, ...y) {
  // y is an Array
  return x * y.length
}

Espansione

fn(...[1, 2, 3])
// same as fn(1, 2, 3)

Parametri predefiniti, parametri rest ed espansione degli argomenti. Function parameters

Funzioni freccia

Funzioni freccia

setTimeout(() => {
  ···
})

Con parametri

readFile('text.txt', (err, data) => {
  ...
})

Risultati impliciti

numbers.map(n => n * 2)
// No curly braces = implicit return
// Same as: numbers.map(function (n) { return n * 2 })
numbers.map(n => ({
  result: n * 2
}))
// Implicitly returning objects requires parentheses around the object

Le funzioni freccia acquisiscono this dall’ambito esterno e non possono fungere da costruttori. Arrow functions

Oggetti

Proprietà abbreviate

module.exports = { hello, bye }
// Same as: module.exports = { hello: hello, bye: bye }

Enhanced object literals

Metodi

const App = {
  start () {
    console.log('running')
  }
}
// Same as: App = { start: function () {···} }

Enhanced object literals

Getter e setter

const App = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}

Enhanced object literals

Nomi di proprietà calcolati

let event = 'click'
let handlers = {
  [`on${event}`]: true
}
// Same as: handlers = { 'onclick': true }

Enhanced object literals

Valori e voci

const fatherJS = { age: 57, name: "Brendan Eich" }

Object.values(fatherJS)
// [57, "Brendan Eich"]
Object.entries(fatherJS)
// [["age", 57], ["name", "Brendan Eich"]]

Moduli

Importazioni

import 'helpers'
// aka: require('···')
import Express from 'express'
// aka: const Express = require('···').default || require('···')
import { indent } from 'helpers'
// aka: const indent = require('···').indent
import * as Helpers from 'helpers'
// aka: const Helpers = require('···')
import { indentSpaces as indent } from 'helpers'
// aka: const indent = require('···').indentSpaces

Gli import ES e require di CommonJS sono meccanismi distinti. I commenti mostrano usi simili. Module imports

Esportazioni

export default function () { ··· }
// aka: module.exports.default = ···
export function mymethod () { ··· }
// aka: module.exports.mymethod = ···
export const pi = 3.14159
// aka: module.exports.pi = ···

export dichiara le esportazioni dei moduli ES. La semantica differisce da module.exports di CommonJS. Module exports

Generatori

Generatori

function* idMaker () {
  let id = 0
  while (true) { yield id++ }
}
let gen = idMaker()
gen.next().value  // → 0
gen.next().value  // → 1
gen.next().value  // → 2

I generatori restituiscono iteratori e si fermano a yield. Generators

Iterazione for-of

for (let i of iterable) {
  ···
}

for-of scorre i valori di un iterabile, come un array o un generatore. For-of iteration

Utilità per le collezioni

const unique = [...new Set([1, 1, 2])];
const scores = new Map([["Ada", 10]]);
for (const [name, score] of scores) console.log(name, score);

Riferimenti

MDN JavaScript guide

Argomenti correlati