Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ES6 for Rubyists

ES6 for Rubyists

Gave this talk at a local Ruby meetup in Sao Paulo. The idea is to show the new version of the JavaScript programming language from a Rubyist perspective.

Video:

https://www.eventials.com/locaweb/lightning-talks-3/

Links:

GURU-SP
https://www.gurusp.org

Netshoes
http://netshoes.com.br

FEMUG-SP
http://sp.femug.com

ZOFE podcast
http://zofe.com.br

XMLHttpRequest
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

jQuery
http://jquery.com

MooTools
http://jquery.com

CoffeeScript
http://coffeescript.org

Source-to-source compilation (transpiling)
http://en.wikipedia.org/wiki/Source-to-source_compiler

Node.js
http://nodejs.org

ES6 Features
https://github.com/lukehoban/es6features

CommonJS
http://wiki.commonjs.org/wiki/CommonJS

AMD
https://github.com/amdjs/amdjs-api/blob/master/AMD.md

Babel
https://babeljs.io

Traceur
https://github.com/google/traceur-compiler

Webpack
http://webpack.github.io

Unofficial ES6 Draft by Mozilla
https://people.mozilla.org/~jorendorff/es6-draft.html

Rafael Rinaldi

February 28, 2015
Tweet

More Decks by Rafael Rinaldi

Other Decks in Technology

Transcript

  1. class Animal # `@` is a reference to `this` constructor:

    (@name) -> move: (meters) -> # String interpolation alert @name + " moved #{meters}m." # Class inheritance support class Snake extends Animal move: -> # No need of parentheses nor semicolons alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = new Snake "Sammy the Python" tom = new Horse "Tommy the Palomino" sam.move() tom.move()
  2. # `::` is a reference to the object’s `prototype` String::dasherize

    = -> # No need to use `return` this.replace /_/g, "-"
  3. ›❯ Fat arrow; ›❯ Array ranges; ›❯ Destructuring of arrays

    and objects; ›❯ String interpolation; ›❯ Heredoc.
  4. ›❯ Block scope; ›❯ Arrow functions; ›❯ Function parameters; ›❯

    Object literals; ›❯ Template strings; ›❯ Better async with Promises and Generators; ›❯ Classes and inheritance; ›❯ Module syntax; ›❯ Module loader.
  5. // ES5 function test() { 'use strict'; if (true) {

    var foo = 'bar'; } console.log(foo); // bar }
  6. // ES6 function test() { if (true) { let foo

    = 'bar'; } console.log(foo); // ReferenceError: foo is not defined }
  7. /** * Arrow functions */ let sum = (x, y)

    => x + y; sum(5, 5); // 10 [1, 2, 3].map(x => x * 2); // 2 4 6
  8. /** * Named parameters */ function addUser(id, {name, age}) {

    console.log(name, age); } addUser(1, {name: 'John Doe', age: 42}); // John Doe 42
  9. /** * Rest parameters */ function setupList(id, ...values) { console.log(id,

    values); } setupList('colors', 'red', 'green', 'blue'); //[ 'red', 'green', 'blue' ]
  10. /** * Spread operator */ let colors = ['red', 'green',

    'blue']; function setupList(id, ...values) { console.log(id, values); } setupList('colors', ...colors); // [ 'red', 'green', 'blue' ]
  11. /** * Object literals */ let object = { //

    Equivalent of `foo: foo` foo, // Method shorthand bar() { return 'baz'; }, // Computed property name ['id-' + (() => 42)()]: 'foo' };
  12. // ES5 multiline through string concatenation var markup = ''

    + '<!doctype html>' + '<html>' + ' <body>' + ' <h1>GURU-SP</h1>' + ' </body>' + '</html>' + '';
  13. // ES5 multiline through escaping new lines var markup =

    '\ <!doctype html>\ <html>\ <body>\ <h1>GURU-SP</h1>\ </body>\ </html>';
  14. // ES5 multiline using an array var markup = [

    '<!doctype html>', '<html>', '<body>', '<h1>GURU-SP</h1>', '</body>', '</html>' ].join('\n');
  15. // Way better in ES6! var markup = ` <!doctype

    html> <html> <body> <h1>GURU-SP</h1> </body> </html>` // String interpolation let name = 'John Doe'; let age = 42; let greetings = `My name is ${name} and I am ${age}`;
  16. // The `*` indicates that this function is a generator

    let iterate = function* () { let index = 0; while(true) { // `yield` will stop the generator and wait for an “answer” to continue yield index += 5; } } // Create the iterator let iterator = iterate(); console.log(iterator.next()); // { value: 5, done: false } console.log(iterator.next()); // { value: 10, done: false } console.log(iterator.next()); // { value: 15, done: false }
  17. // Simple XHR request implementation function ping(url) { // Return

    a new promise return new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); request.open('GET', url); request.onload = function() { if (request.status == 200) { // Resolve the promise with the response text resolve(request.response); } else { // Otherwise reject with the status text // which will hopefully be a meaningful error reject(Error(request.statusText)); } }; // Make the actual request request.send(); }); }
  18. // The good old prototypal inheritance function Color() {} Color.prototype.setHexa

    = function(code) { this.hexa = code; } Color.prototype.toString = function() { return this.hexa; } function Yellow() { this.setHexa('#ffd200'); } function Blue() { this.setHexa('#00cdfa'); } Yellow.prototype = Object.create(Color.prototype); Blue.prototype = Object.create(Color.prototype); var x = new Yellow(); var y = new Blue(); console.log(x.toString()); // #ffd200 console.log(y.toString()); // #00cdfa
  19. class Color { set hexa(code) { this._hexa = code; }

    get hexa() { return this._hexa; } toString() { return this.hexa; } } class Yellow extends Color { constructor() { this.hexa = '#ffd200'; } } class Blue extends Color { constructor() { this.hexa = '#00cdfa'; } } let x = new Yellow(); let y = new Blue(); console.log(x.toString()); // #ffd200 console.log(y.toString()); // #00cdfa
  20. /** * Example of CommonJS module */ // Self contained

    module, the file itself is a clojure // List of module’s dependencies var IO = require('fs/io'); var pluck = require('helpers').pluck; // Exports the public API module.exports = { toString: function() { return 42; } };
  21. /** * Example of AMD module */ // Pass on

    a list of dependencies and the module implementation define(['fs/io', 'helpers/pluck'], function(IO, pluck) { // Module implementation goes here // Exports the public API return { toString: function() { return 42; } } });
  22. // Import a module from a package import 'io' from

    'fs/io'; // Named imports import {pluck, sort} from 'helpers'; // Wildcard and module aliasing import * as core from 'core'; // Exports `toString` to the public API export let toString = () => 42; // Exports a constant to the public API export const PI = 3.14; // You can also export a module default function export default function() { console.log('Default function!'); }