DEV Community

luiz tanure
luiz tanure

Posted on • Originally published at letanure.dev

Exploring ECMAScript 2015 (ES6) Features

Note: This article was originally published on January 15, 2015. Some information may be outdated.

ECMAScript 2015 (ES6) adds modern syntax, safer defaults, and built‑in tools for async and modular code.

Transpile with Babel:

npm init -y
npm install --save-dev @babel/core @babel/cli @babel/preset-env
echo '{ "presets": ["@babel/preset-env"] }' > .babelrc
npx babel src --out-dir dist
Enter fullscreen mode Exit fullscreen mode

Place ES6 files in src/, run the command, and load the output from dist/ in older browsers.


Feature list


let and const

for (let i = 0; i < 3; i++) {
  // i scoped to loop only
}
const API_URL = '/api';
Enter fullscreen mode Exit fullscreen mode

Arrow functions

const doubled = [1, 2, 3].map(n => n * 2);
button.addEventListener('click', () => this.save());
Enter fullscreen mode Exit fullscreen mode

Template literals

const user = 'Luiz';
const msg = `Hi, ${user}
Welcome to ES6.`;
Enter fullscreen mode Exit fullscreen mode

Destructuring

const [red, green] = ['#f00', '#0f0'];

const user = { id: 7, role: 'admin' };
const { id, role } = user;
Enter fullscreen mode Exit fullscreen mode

Default, rest, spread

function greet(name = 'guest') { return `Hi ${name}`; }

const nums = [1, 2, 3];
sum(...nums); // spread into args

function logAll(...args) { console.log(args); }
Enter fullscreen mode Exit fullscreen mode

Enhanced object literals

const name = 'x';
const obj = {
  name,                // shorthand
  [`prop_${name}`]: 1, // computed key
  toString() { return this.name; }
};
Enter fullscreen mode Exit fullscreen mode

Classes

class Counter {
  constructor(start = 0) { this.count = start; }
  inc() { return ++this.count; }
}
Enter fullscreen mode Exit fullscreen mode

Modules

// math.js
export const PI = 3.14;

// app.js
import { PI } from './math.js';
console.log(PI);
Enter fullscreen mode Exit fullscreen mode

Run through Babel or a bundler to use modules in the browser.


Promises

fetch('/data.json')
  .then(r => r.json())
  .then(show)
  .catch(console.error);
Enter fullscreen mode Exit fullscreen mode

Iterators and for..of

for (const n of [10, 20, 30]) {
  console.log(n);
}
Enter fullscreen mode Exit fullscreen mode

Generators

function* idMaker() {
  let id = 0;
  while (true) yield id++;
}
const gen = idMaker();
gen.next().value; // 0
Enter fullscreen mode Exit fullscreen mode

Map, Set, WeakMap, WeakSet

const ids = new Set([1, 2, 2, 3]); // {1,2,3}
const dict = new Map([['key', 42]]);
Enter fullscreen mode Exit fullscreen mode

Symbols

const secret = Symbol('secret');
const obj = { [secret]: 123 };
Enter fullscreen mode Exit fullscreen mode

Unicode & binary/octal

'𝌆'.length; // 2 in ES5, fixed helpers in ES6

0b1010; // 10
0o755;  // 493
Enter fullscreen mode Exit fullscreen mode

New APIs

Number.isNaN(NaN);      // true
[1, 2, 3].includes(2);  // true
Math.trunc(4.8);        // 4
Object.assign({}, { a: 1 });
Enter fullscreen mode Exit fullscreen mode

Proxies

const monitor = new Proxy({}, {
  get(target, prop) {
    console.log('read', prop);
    return target[prop];
  }
});
monitor.x = 5;
monitor.x; // logs "read x"
Enter fullscreen mode Exit fullscreen mode

Reflect API

const obj = {};
Reflect.set(obj, 'x', 1);
Reflect.get(obj, 'x'); // 1
Enter fullscreen mode Exit fullscreen mode

Tail‑call optimisation

function factorial(n, acc = 1) {
  return n === 0 ? acc : factorial(n - 1, n * acc);
}
Enter fullscreen mode Exit fullscreen mode

Tail‑recursive functions can run without growing the call stack in compliant engines.

Top comments (0)