Javascript ES6
ECMAScript 2015 foi a segunda grande revisão do JavaScript.
ECMAScript 2015 também é conhecido como ES6 e ECMAScript 6.
Este capítulo descreve os recursos mais importantes do ES6.
Novos recursos no ES6
- A palavra-chave let
- A palavra-chave const
- Funções de seta
- Para de
- Objetos de mapa
- Definir objetos
- Aulas
- Promessas
- Símbolo
- Parâmetros padrão
- Parâmetro de descanso da função
- String.includes()
- String.startsWith()
- String.endsWith()
- Matriz.de()
- Chaves de matriz()
- Encontrar matriz()
- Array findIndex()
- Novos métodos matemáticos
- Propriedades do novo número
- Novos métodos de número
- Novos métodos globais
- Iterables Object.entries
- Módulos JavaScript
Suporte do navegador para ES6 (2015)
Safari 10 e Edge 14 foram os primeiros navegadores a oferecer suporte total ao ES6:
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
JavaScript permite
A let
palavra-chave permite declarar uma variável com escopo de bloco.
Exemplo
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Leia mais sobre let
no capítulo: JavaScript Let .
JavaScript const
A const
palavra-chave permite declarar uma constante (uma variável JavaScript com um valor constante).
As constantes são semelhantes às variáveis let, exceto que o valor não pode ser alterado.
Exemplo
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Leia mais sobre const
no capítulo: JavaScript Const .
Funções de seta
As funções de seta permitem uma sintaxe curta para escrever expressões de função.
Você não precisa da palavra- function
chave, da palavra- return
chave e das
chaves .
Exemplo
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
As funções de seta não têm seu próprio this
. Eles não são adequados para definir métodos de objetos .
As funções de seta não são içadas. Eles devem ser definidos antes de serem usados.
Usar const
é mais seguro do que usar var
, porque uma expressão de função é sempre um valor constante.
Você só pode omitir a return
palavra-chave e as chaves se a função for uma única instrução. Por isso, pode ser um bom hábito mantê-los sempre:
Exemplo
const x = (x, y) => { return x * y };
Saiba mais sobre as funções de seta no capítulo: Função de seta JavaScript .
O loop for/of
A instrução JavaScript for/of
percorre os valores de um objeto iterável.
for/of
permite que você faça um loop sobre estruturas de dados que são iteráveis, como Arrays, Strings, Maps, NodeLists e muito mais.
O for/of
loop tem a seguinte sintaxe:
for (variable of iterable) {
// code block to be executed
}
variável - Para cada iteração, o valor da próxima propriedade é atribuído à variável. A variável pode ser declarada com
const
, let
ou var
.
iterável - Um objeto que tem propriedades iteráveis.
Loop sobre uma matriz
Exemplo
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Loop sobre uma String
Exemplo
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Saiba mais no capítulo: JavaScript Loop For/In/Of .
Objetos de mapa JavaScript
Ser capaz de usar um Objeto como chave é um importante recurso do Mapa.
Exemplo
// 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);
Saiba mais sobre objetos Map no capítulo: JavaScript Map() .
Objetos de conjunto JavaScript
Exemplo
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Aprenda mais sobre objetos Set no capítulo: JavaScript Set() .
Classes JavaScript
Classes JavaScript são modelos para objetos JavaScript.
Use a palavra-chave class
para criar uma classe.
Sempre adicione um método chamado constructor()
:
Sintaxe
class ClassName {
constructor() { ... }
}
Exemplo
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
O exemplo acima cria uma classe chamada "Car".
A classe tem duas propriedades iniciais: "nome" e "ano".
Uma classe JavaScript não é um objeto.
É um modelo para objetos JavaScript.
Usando uma classe
Quando você tem uma classe, você pode usar a classe para criar objetos:
Exemplo
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Saiba mais sobre classes no capítulo: Classes JavaScript .
Promessas de JavaScript
Uma promessa é um objeto JavaScript que vincula "Código de produção" e "Código de consumo".
"Produzir Código" pode levar algum tempo e "Consumir Código" deve aguardar o resultado.
Sintaxe da 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 */ }
);
Exemplo usando uma promessa
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Saiba mais sobre Promises no capítulo: Promises JavaScript .
O tipo de símbolo
Um símbolo JavaScript é um tipo de dados primitivo como Number, String ou Boolean.
Ele representa um identificador exclusivo "oculto" que nenhum outro código pode acessar acidentalmente.
Por exemplo, se diferentes codificadores quiserem adicionar uma propriedade person.id a um objeto pessoa pertencente a um código de terceiros, eles podem misturar os valores uns dos outros.
Usando Symbol() para criar identificadores exclusivos, resolve este problema:
Exemplo
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
Os símbolos são sempre únicos.
Se você criar dois símbolos com a mesma descrição, eles terão valores diferentes.
Symbol("id") == Symbol("id") // false
Valores de parâmetro padrão
O ES6 permite que os parâmetros de função tenham valores padrão.
Exemplo
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
Parâmetro de descanso da função
O parâmetro rest (...) permite que uma função trate um número indefinido de argumentos como um array:
Exemplo
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.includes()
O includes()
método retorna true
se uma string contiver um valor especificado, caso contrário false
:
Exemplo
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
String.startsWith()
O startsWith()
método retorna true
se uma string começa com um valor especificado, caso contrário false
:
Exemplo
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
String.endsWith()
O endsWith()
método retorna true
se uma string termina com um valor especificado, caso contrário false
:
Exemplo
var text = "John Doe";
text.endsWith("Doe") // Returns true
Matriz.de()
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