Comenzando con ES6 usando algunas de mis cosas favoritas

Este tutorial lo guía a través de algunos pasos sencillos para comenzar a aprender la versión más reciente de JavaScript: ES6.

Para tener una idea del idioma, profundizaremos en algunas de mis características favoritas. Luego, proporcionaré una breve lista de excelentes recursos para aprender ES6.

¿ES6 o ECMAScript 2015?

"¿Lo que hay en un nombre?"

- Julieta de "Romeo y Julieta" de Shakespeare

El nombre oficial de la sexta edición de ECMAScript es ECMAScript 2015, ya que se finalizó en junio de 2015. Sin embargo, en general, la gente parece referirse a ella simplemente como ES6 .

Anteriormente, tenía que usar un transpilador como Babel para incluso comenzar con ES6. Ahora, parece que casi todo el mundo, excepto Microsoft Internet Explorer, admite la mayoría de las funciones de ES6. Para ser justos, Microsoft admite ES6 en Edge. Si desea obtener más detalles, consulte la tabla de compatibilidad de kangax .

Entorno de aprendizaje ES6

La mejor forma de aprender ES6 es escribir y ejecutar ES6. Hay muchas formas de hacerlo. Pero los dos que uso cuando estoy experimentando son:

  • Node.js
  • Página de prueba de Babel.io

Node.js y Visual Studio Code

Una de las mejores formas de explorar las cortesías de ES6 es escribir su código en un editor como Visual Studio Code y luego ejecutarlo en Node.js

Instale Visual Studio Code y cree un archivo llamado helloworld.js. Pegue el siguiente código en:

console.log('Hello world');

Guárdalo. Debería verse algo como esto:

Desde la versión 6.5, Node.js ha admitido la mayor parte del estándar ES6. Para ejecutar nuestro ejemplo, abra el símbolo del sistema de Node.js en su carpeta donde creó el helloworld.jsarchivo. Y, simplemente escriba:

node helloworld.js

Nuestra console.logdeclaración se imprime como salida:

Babel.io

No es tan divertido como Node.js, pero una forma conveniente de ejecutar el código ES6 es la página Pruébelo en Babel.io. Expanda la Configuración y asegúrese de que Evaluar esté marcado. Luego abra la consola de su navegador .

Escriba el ES6 en la columna de la izquierda. Babel lo compila en JavaScript antiguo. Puede usar console.logy ver el resultado en la consola web a la derecha.

Algunas de mis funciones favoritas

"Estas son algunas de mis cosas favoritas."

- Maria de "The Sound of Music" de Rodgers y Hammerstein

En esta sección, echaremos un vistazo rápido a algunas de las nuevas funciones de ES6, que incluyen:

  • Usando lety en constlugar devar
  • Funciones de flecha
  • Cadenas de plantilla
  • Desestructuración

const y deja Versus var

Ahora que está codificando en ES6: ¡Deje de usar var! En serio, nunca lo varvuelva a usar .

De ahora en adelante, use consto let. Úselo constcuando establezca el valor una vez. Úselo letcuando desee cambiar el valor.

let bar = { x: 'x'};const foo = { x: 'x'};
bar.x = 'other'; // This is finefoo.x = 'other'; // This is fine
bar = {}; // This is also finefoo = {}; // This will throw an error

Normalmente, me gusta usar constprimero. Luego, si se queja, miro mi código y me aseguro de que realmente necesito poder modificar la variable. Si es así, lo cambio a let.

Asegúrese de consultar los recursos más adelante en este artículo para obtener más información sobre lety const. Verás que funcionan de forma mucho más intuitiva que var.

Funciones de flecha

Las funciones de flecha son una de las características definitorias de ES6. Las funciones de flecha son una nueva forma de escribir funciones. Por ejemplo, las siguientes funciones funcionan de manera idéntica:

function oneMore(val){ return val+1;}console.log('3 and one more is:', oneMore(3));
const oneMore = (val) => val+1;console.log('3 and one more is:', oneMore(3));

Hay algunas cosas para recordar acerca de las funciones de flecha:

  • Devuelven automáticamente el valor calculado.
  • Tienen léxico this.

La primera vez que vi esto me pregunté: “¿Qué diablos es un léxico esto ? Y, ¿realmente me importa? Veamos un ejemplo de por qué el léxico this es tan útil y cómo hace que nuestro código sea mucho más intuitivo:

In lines 1–31, we define a Class called ThisTester. It has two functions thisArrowTest() and thisTest() that basically do the same thing. But, one uses an arrow function and the other uses the classic function notation.

On line 33, we create an new object myTester based on our ThisTester class and call the two functions in our class.

const myTester = new ThisTester();console.log('TESTING: thisArrowTest');myTester.thisArrowTest();console.log('');console.log('TESTING: thisTest');myTester.thisTest();

In the thisTest() function, we see that it tries to use this in line 26.

console.log('function this fails', this.testValue);

But, it fails because that function gets its own this and it isn’t the same this as the class. If you think this is confusing, that’s because it is. It isn’t intuitive at all. And, new developers sometimes spend their first week fighting with this in callback functions and promises like I did.

Eventually, after reviewing a bunch of examples, I figured out the standard “trick” of using a variable called self to hold onto the this that we want to use. For example, in line 17:

let self = this;

However, notice how in the arrow function in line 10, we can directly access this.testValue and magically it works:

let myFunction = (x) =>console.log('arrow "this" works:', this.testValue)

That is lexical this in action. The this in the arrow function is the same as the this in the surrounding function that calls it. And hence we can intuitively use this to access the properties in our object like this.testValue.

Template Strings

Template Strings (sometimes called Template Literals) are an easy way to construct strings. They are great for multi line strings such as those used in Angular templates. Template Strings use the back tick ` instead of quote or apostrophe.

Here is an example of creating a long, multi-line string:

const myLongString = `This stringactually spans many lines.And, I don't even need to use any "strange"notation.`;console.log (myLongString);

You can easily bind variables to your string, for example:

const first = 'Todd', last = 'Palmer';console.log(`Hello, my name is ${first} ${last}.`)

Looking at that variable assignment begs the question:

“What if I need to use the $, {, or } characters in my string?”

Well, the only one that needs special treatment is the sequence ${.

console.log(`I can use them all separately $ { }`);console.log(`$\{ needs a backslash.`);

Template Strings are especially useful in Angular and AngularJS where you create HTML templates, because they tend to be multi-line and have a lot of quotes and apostrophes. Here is what a small example of an Angular Template leveraging the back tick looks like:

import { Component } from '@angular/core';
@Component({ selector: 'app-root', template: ` 

{{title}}

My favorite hero is: {{myHero}}

`})export class AppComponent { title = 'Tour of Heroes'; myHero = 'Windstorm';}

Destructuring

Destructuring lets you take parts of an object or array and assign them to your own named variables. For more information on Destructuring, check out my article on ITNEXT.

ES6 Resources

That was just a quick overview of a few of the new features in ES6. Here are some great resources for continuing your journey down the path of learning ES6:

  • Learn ES2015 on Babel

    This is an overview of all the new features. Although it doesn’t go into much depth, this is a great page to keep as a quick reference with examples.

  • ES6 tips and tricks to make your code cleaner, shorter, and easier to read! by Sam Williams

    This is a great article in Free Code Camp’s Medium publication.

  • MPJ’s video series: ES6 JavaScript Features

    If you prefer videos, MPJ is your guy. Not only is he good technically, his stuff is really entertaining.

  • ES6 in Depth series on Mozilla Hacks

    This is an excellent in depth series.

  • Eric Elliott’s series Composing Software

    Read through this one for a real challenge. Be forewarned though, some of Eric’s stuff is college level Computer Science.

This article is based on a lecture I gave in March 2018.