Javascript ES6
ECMAScript 2015 è stata la seconda revisione importante di JavaScript.
ECMAScript 2015 è anche noto come ES6 e ECMAScript 6.
Questo capitolo descrive le caratteristiche più importanti di ES6.
Nuove funzionalità in ES6
- La parola chiave let
- La parola chiave const
- Funzioni delle frecce
- Per/di
- Mappa oggetti
- Impostare gli oggetti
- Classi
- Promesse
- Simbolo
- Parametri predefiniti
- Parametro di riposo della funzione
- String.include()
- String.startsWith()
- String.endsWith()
- Array.da()
- Chiavi matrice()
- Trova matrice()
- array findIndex()
- Nuovi metodi matematici
- Nuove proprietà numeriche
- Nuovi metodi numerici
- Nuovi metodi globali
- Iterables Object.entries
- Moduli JavaScript
Supporto browser per ES6 (2015)
Safari 10 ed Edge 14 sono stati i primi browser a supportare completamente ES6:
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
JavaScript lascia
La let
parola chiave consente di dichiarare una variabile con ambito di blocco.
Esempio
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Maggiori informazioni let
nel capitolo: JavaScript Let .
JavaScript cost
La const
parola chiave consente di dichiarare una costante (una variabile JavaScript con un valore costante).
Le costanti sono simili alle variabili let, tranne per il fatto che il valore non può essere modificato.
Esempio
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Maggiori informazioni const
nel capitolo: JavaScript Const .
Funzioni delle frecce
Le funzioni delle frecce consentono una breve sintassi per la scrittura di espressioni di funzione.
Non sono necessarie la function
parola chiave, la return
parola chiave e le
parentesi graffe .
Esempio
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Le funzioni delle frecce non hanno le proprie this
. Non sono adatti per definire metodi oggetto .
Le funzioni delle frecce non sono sollevate. Devono essere definiti prima di essere utilizzati.
L'utilizzo const
è più sicuro dell'utilizzo var
, poiché un'espressione di funzione è sempre un valore costante.
Puoi omettere la return
parola chiave e le parentesi graffe solo se la funzione è una singola istruzione. Per questo motivo, potrebbe essere una buona abitudine tenerli sempre:
Esempio
const x = (x, y) => { return x * y };
Ulteriori informazioni sulle funzioni freccia nel capitolo: Funzione freccia JavaScript .
Il ciclo for/of
L'istruzione JavaScript for/of
scorre i valori di un oggetto iterabile.
for/of
ti consente di scorrere strutture di dati che sono iterabili come matrici, stringhe, mappe, elenchi di nodi e altro.
Il for/of
ciclo ha la seguente sintassi:
for (variable of iterable) {
// code block to be executed
}
variabile - Ad ogni iterazione viene assegnato alla variabile il valore della proprietà successiva. La variabile può essere dichiarata con
const
, let
, o var
.
iterable - Un oggetto con proprietà iterabili.
Ciclo su un array
Esempio
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Ciclo su una stringa
Esempio
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Ulteriori informazioni nel capitolo: JavaScript Loop For/In/Of .
Oggetti mappa JavaScript
Essere in grado di utilizzare un oggetto come chiave è una caratteristica importante della mappa.
Esempio
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
// Create a new Map
const fruits = new Map();
// Add new Elements to the Map
fruits.set(apples, 500);
fruits.set(bananas, 300);
fruits.set(oranges, 200);
Scopri di più sugli oggetti Map nel capitolo: JavaScript Map() .
JavaScript imposta oggetti
Esempio
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Scopri di più sugli oggetti Set nel capitolo: JavaScript Set() .
Classi JavaScript
Le classi JavaScript sono modelli per oggetti JavaScript.
Usa la parola chiave class
per creare una classe.
Aggiungi sempre un metodo chiamato constructor()
:
Sintassi
class ClassName {
constructor() { ... }
}
Esempio
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
L'esempio sopra crea una classe denominata "Car".
La classe ha due proprietà iniziali: "name" e "year".
Una classe JavaScript non è un oggetto.
È un modello per oggetti JavaScript.
Usando una classe
Quando hai una classe, puoi usare la classe per creare oggetti:
Esempio
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Scopri di più sulle classi nel capitolo: Classi JavaScript .
JavaScript Promesse
Una promessa è un oggetto JavaScript che collega "Codice di produzione" e "Codice di consumo".
"Produrre codice" può richiedere del tempo e "Codice consumo" deve attendere il risultato.
Sintassi della promessa
const myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});
// "Consuming Code" (Must wait for a fulfilled Promise).
myPromise.then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Esempio usando una promessa
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Scopri di più su Promise nel capitolo: JavaScript Promises .
Il tipo di simbolo
Un simbolo JavaScript è un tipo di dati primitivo proprio come Number, String o Boolean.
Rappresenta un identificatore univoco "nascosto" a cui nessun altro codice può accedere accidentalmente.
Ad esempio, se diversi programmatori desiderano aggiungere una proprietà person.id a un oggetto person appartenente a un codice di terze parti, possono combinare i valori l'uno con l'altro.
L'utilizzo di Symbol() per creare identificatori univoci risolve questo problema:
Esempio
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
let id = Symbol('id');
person[id] = 140353;
// Now person[id] = 140353
// but person.id is still undefined
I simboli sono sempre unici.
Se crei due simboli con la stessa descrizione avranno valori diversi.
Symbol("id") == Symbol("id") // false
Valori di default dei parametri
ES6 consente ai parametri di funzione di avere valori predefiniti.
Esempio
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
Parametro di riposo della funzione
Il parametro rest (...) consente a una funzione di trattare un numero indefinito di argomenti come un array:
Esempio
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
String.include()
Il includes()
metodo restituisce true
se una stringa contiene un valore specificato, altrimenti false
:
Esempio
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
String.startsWith()
Il startsWith()
metodo restituisce true
se una stringa inizia con un valore specificato, altrimenti false
:
Esempio
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
String.endsWith()
Il endsWith()
metodo restituisce true
se una stringa termina con un valore specificato, altrimenti false
:
Esempio
var text = "John Doe";
text.endsWith("Doe") // Returns true
Array.da()
The Array.from()
method returns an Array object from any object with a length
property or any iterable object.
Example
Create an Array from a String:
Array.from("ABCDEFG") // Returns [A,B,C,D,E,F,G]
Array keys()
The keys()
method returns an Array Iterator object with the keys of an array.
Example
Create an Array Iterator object, containing the keys of the array:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
const keys = fruits.keys();
let text = "";
for (let x of keys) {
text += x + "<br>";
}
Array find()
The find()
method returns the value of the first array element that passes a
test function.
This example finds (returns the value of ) the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.find(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
Array findIndex()
The findIndex()
method returns the index of the first array element that
passes a test function.
This example finds the index of the first element that is larger than 18:
Example
const numbers = [4, 9, 16, 25, 29];
let first =
numbers.findIndex(myFunction);
function myFunction(value, index, array) {
return
value > 18;
}
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
New Math Methods
ES6 added the following methods to the Math object:
Math.trunc()
Math.sign()
Math.cbrt()
Math.log2()
Math.log10()
The Math.trunc() Method
Math.trunc(x)
returns the integer part of x:
Example
Math.trunc(4.9); // returns 4
Math.trunc(4.7); // returns 4
Math.trunc(4.4); // returns 4
Math.trunc(4.2); // returns 4
Math.trunc(-4.2); // returns -4
The Math.sign() Method
Math.sign(x)
returns if x is negative, null or positive:
Example
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1
The Math.cbrt() Method
Math.cbrt(x)
returns the cube root of x:
Example
Math.cbrt(8); // returns 2
Math.cbrt(64); // returns 4
Math.cbrt(125); // returns 5
The Math.log2() Method
Math.log2(x)
returns the base 2 logarithm of x:
Example
Math.log2(2); // returns 1
The Math.log10() Method
Math.log10(x)
returns the base 10 logarithm of x:
Example
Math.log10(10); // returns 1
New Number Properties
ES6 added the following properties to the Number object:
EPSILON
MIN_SAFE_INTEGER
MAX_SAFE_INTEGER
Example
let x = Number.EPSILON;
Example
let x = Number.MIN_SAFE_INTEGER;
Example
let x = Number.MAX_SAFE_INTEGER;
New Number Methods
ES6 added 2 new methods to the Number object:
Number.isInteger()
Number.isSafeInteger()
The Number.isInteger() Method
The Number.isInteger()
method returns true
if the argument is an integer.
Example
Number.isInteger(10); // returns true
Number.isInteger(10.5); // returns false
The Number.isSafeInteger() Method
A safe integer is an integer that can be exactly represented as a double precision number.
The Number.isSafeInteger()
method returns true
if the argument is a safe integer.
Example
Number.isSafeInteger(10); // returns true
Number.isSafeInteger(12345678901234567890); // returns false
Safe integers are all integers from -(253 - 1) to +(253 - 1).
This is safe: 9007199254740991. This is not safe: 9007199254740992.
New Global Methods
ES6 added 2 new global number methods:
isFinite()
isNaN()
The isFinite() Method
The global isFinite()
method returns false
if the argument is Infinity
or NaN
.
Otherwise it returns true
:
Example
isFinite(10/0); // returns false
isFinite(10/1); // returns true
The isNaN() Method
The global isNaN()
method returns true
if the argument is NaN
. Otherwise it returns false
:
Example
isNaN("Hello"); // returns true