JavaScript ES6
ECMAScript 2015 fue la segunda revisión importante de JavaScript.
ECMAScript 2015 también se conoce como ES6 y ECMAScript 6.
Este capítulo describe las funciones más importantes de ES6.
Nuevas características en ES6
- La palabra clave let
- La palabra clave constante
- Funciones de flecha
- para/de
- Objetos del mapa
- Establecer objetos
- Clases
- promesas
- Símbolo
- Parámetros predeterminados
- Parámetro de reposo de función
- Cadena.incluye()
- String.empiezaCon()
- Cadena.termina con()
- matriz.desde()
- Arreglos de claves()
- búsqueda de matriz ()
- Array findIndex()
- Nuevos métodos matemáticos
- Propiedades de nuevos números
- Nuevos métodos numéricos
- Nuevos métodos globales
- Iterables Object.entries
- Módulos JavaScript
Soporte de navegador para ES6 (2015)
Safari 10 y Edge 14 fueron los primeros navegadores en ser totalmente compatibles con ES6:
Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
Jan 2017 | Aug 2016 | Mar 2017 | Jul 2016 | Aug 2018 |
JavaScript permite
La let
palabra clave le permite declarar una variable con alcance de bloque.
Ejemplo
var x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Obtenga más información let
en el capítulo: JavaScript Let .
constante de JavaScript
La const
palabra clave le permite declarar una constante (una variable de JavaScript con un valor constante).
Las constantes son similares a las variables let, excepto que el valor no se puede cambiar.
Ejemplo
var x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Obtenga más información const
en el capítulo: JavaScript Const .
Funciones de flecha
Las funciones de flecha permiten una sintaxis corta para escribir expresiones de funciones.
No necesita la function
palabra clave, la return
palabra clave y las
llaves .
Ejemplo
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Las funciones de flecha no tienen las suyas propias this
. No son adecuados para definir métodos de objetos .
Las funciones de flecha no se elevan. Deben definirse antes de que se utilicen.
Usar const
es más seguro que usar var
, porque una expresión de función siempre es un valor constante.
Solo puede omitir la return
palabra clave y las llaves si la función es una declaración única. Por eso, puede ser un buen hábito conservarlos siempre:
Ejemplo
const x = (x, y) => { return x * y };
Obtenga más información sobre las funciones de flecha en el capítulo: Función de flecha de JavaScript .
El bucle for/of
La declaración de JavaScript for/of
recorre los valores de un objeto iterable.
for/of
le permite recorrer estructuras de datos que son iterables, como Arrays, Strings, Maps, NodeLists y más.
El for/of
bucle tiene la siguiente sintaxis:
for (variable of iterable) {
// code block to be executed
}
variable : para cada iteración, el valor de la siguiente propiedad se asigna a la variable. La variable se puede declarar con
const
, let
o var
.
iterable : un objeto que tiene propiedades iterables.
Bucle sobre una matriz
Ejemplo
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x + " ";
}
Bucle sobre una cadena
Ejemplo
let language = "JavaScript";
let text = "";
for (let x of language) {
text += x + " ";
}
Obtenga más información en el capítulo: JavaScript Loop For/In/Of .
Objetos de mapa de JavaScript
Poder usar un objeto como clave es una característica importante del mapa.
Ejemplo
// 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);
Obtenga más información sobre los objetos Map en el capítulo: JavaScript Map() .
Objetos de conjunto de JavaScript
Ejemplo
// Create a Set
const letters = new Set();
// Add some values to the Set
letters.add("a");
letters.add("b");
letters.add("c");
Obtenga más información sobre los objetos Set en el capítulo: JavaScript Set() .
Clases de JavaScript
Las clases de JavaScript son plantillas para objetos de JavaScript.
Utilice la palabra clave class
para crear una clase.
Siempre agregue un método llamado constructor()
:
Sintaxis
class ClassName {
constructor() { ... }
}
Ejemplo
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
El ejemplo anterior crea una clase llamada "Car".
La clase tiene dos propiedades iniciales: "nombre" y "año".
Una clase JavaScript no es un objeto.
Es una plantilla para objetos de JavaScript.
usando una clase
Cuando tienes una clase, puedes usar la clase para crear objetos:
Ejemplo
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Obtenga más información sobre las clases en el capítulo: Clases de JavaScript .
Promesas de JavaScript
Una promesa es un objeto de JavaScript que vincula el "código de producción" y el "código de consumo".
"Producir código" puede tardar algún tiempo y "Consumir código" debe esperar el resultado.
Sintaxis de promesa
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 */ }
);
Ejemplo usando una promesa
const myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
myPromise.then(function(value) {
document.getElementById("demo").innerHTML = value;
});
Obtenga más información sobre Promesas en el capítulo: Promesas de JavaScript .
El tipo de símbolo
Un símbolo de JavaScript es un tipo de datos primitivo como Number, String o Boolean.
Representa un identificador único "oculto" al que ningún otro código puede acceder accidentalmente.
Por ejemplo, si diferentes codificadores quieren agregar una propiedad person.id a un objeto de persona que pertenece a un código de terceros, podrían mezclar los valores de los demás.
El uso de Symbol() para crear identificadores únicos resuelve este problema:
Ejemplo
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
Los símbolos son siempre únicos.
Si crea dos símbolos con la misma descripción, tendrán valores diferentes.
Symbol("id") == Symbol("id") // false
Valores de parámetros predeterminados
ES6 permite que los parámetros de función tengan valores predeterminados.
Ejemplo
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y;
}
myFunction(5); // will return 15
Parámetro de reposo de función
El parámetro rest (...) permite que una función trate un número indefinido de argumentos como una matriz:
Ejemplo
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);
Cadena.incluye()
El includes()
método devuelve true
si una cadena contiene un valor específico, de lo contrario false
:
Ejemplo
let text = "Hello world, welcome to the universe.";
text.includes("world") // Returns true
String.empiezaCon()
El startsWith()
método regresa true
si una cadena comienza con un valor específico, de lo contrario false
:
Ejemplo
let text = "Hello world, welcome to the universe.";
text.startsWith("Hello") // Returns true
Cadena.termina con()
El endsWith()
método regresa true
si una cadena termina con un valor específico, de lo contrario false
:
Ejemplo
var text = "John Doe";
text.endsWith("Doe") // Returns true
matriz.desde()
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