Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

ES6: Features + Rails

531 views

Published on

ES6 features + rails

Published in: Technology
  • Be the first to comment

  • Be the first to like this

ES6: Features + Rails

  1. 1. ES6Features & Rails Santosh Wadghule @mechanicles
  2. 2. ES6 + Its Features + Setup on Rails
  3. 3. ES6? What is it?
  4. 4. ES6 • ES6 is short name of “ECMAScript Language Specification, Edition 6” • It’s a new version of ECMAScript • ECMAScript is the official name of JavaScript • ES6 provides very nice powerful features • ES6 helps writing more modular and less quirky code in JavaScript.
  5. 5. ES6 Features
  6. 6. ES6 Features • Let + Const • Template string • Destructuring Assignment • Default + Rest + Spread • Loops, Generators • Enhanced object literals • Map + Set • Arrows • Modules • Classes
  7. 7. Let + Const
  8. 8. Let + Const • Variables before ES6 are function scoped • ‘let’ & ‘const’ are block-scoped binding constructs • ‘let’ is the new variable • ‘const’ is single-assignment.
  9. 9. Let
  10. 10. // ES5 "use strict"; function superHeroes() { var superHero1; { superHero1 = "Spider-Man"; var superHero2 = "Batman"; console.log(superHero1); // => "Spider-Man" console.log(superHero2); // => "Batman" } console.log(superHero1); // => "Spider-Man" console.log(superHero2); // => "Batman" } superHeroes();
  11. 11. function superHeroes() { let superHero1; { superHero1 = "Spider-Man"; let superHero2 = "Batman"; console.log(superHero1); // => "Spider-Man" console.log(superHero2); // => "Batman" } console.log(superHero1); // => "Spider-Man" console.log(superHero2); // => "superHero2 is not defined" } superHeroes();
  12. 12. Const
  13. 13. // ES6 function superHeroes(){ const NAME = 'HULK' { const COLOUR = 'green' console.log(NAME); // => 'HULK' console.log(COLOUR); // => 'green' } console.log(NAME); // => 'HULK' console.log(COLOUR); // => COLOUR is not defined } superHeroes();
  14. 14. // ES6 function superHeroes(){ const NAME = 'HULK' { const COLOUR = 'green' console.log(NAME); console.log(COLOUR); NAME = 'other_name'; } console.log(NAME); console.log(COLOUR); } superHeroes(); // Error: ”NAME" is read-only
  15. 15. Template Strings
  16. 16. Template Strings • A new way of string interpolation • It adds syntactic sugar for constructing strings • Easy to handle multiline strings
  17. 17. // ES6 // basic template string creation. var str = `How you doing?`; var name = 'Joey'; var output = `${name}: ${str}`; console.log(output) // => Joey: How you doing? var first_name = 'john'; var last_name = 'smith'; // Instead of handlling this stuff 'HTTP://example.com/first_name=' + first_name + '&last_name=' + last_name // we can do this very easily. `HTTP://example.com/first_name=${first_name}&last_name=${last_name}` // Multiple Strings. `Oh, I'm sory, Did I break your concentration?` // => Oh, I'm sory, // => Did I break your concentration?
  18. 18. Enhanced Object Literals
  19. 19. Enhanced Object Literals • Object literal is the most popular pattern in JavaScript • Based on its syntax, JSON was built • ES6 recognised the popularity of the object literal and extended it in several ways to make it more powerful and even more succinct
  20. 20. Property Initializer Shorthand // ES5 function createPost(title, content) { return { title: title, content: content }; } //ES6 function createPost(title, content) { return { title, content }; }
  21. 21. Method Initializer Shorthand // ES5 var car = { name: "Mustang GT500", startEngine: function() { console.log('starting...'); } }; //ES6 var car = { name: "Mustang GT500", startEngine(){ console.log('starting...'); } };
  22. 22. Computed Property Names // ES5 var car = { "name": "Mustang GT500" }; console.log(car["name"]); // "Mustang GT500" // ES6 var maxSpeed = "max speed"; var prefix = "min "; var car = { "name": "Mustang GT500", [maxSpeed]: "160", [prefix + "speed"]: "0" }; console.log(car["name"]); // "Mustang GT500" console.log(car["max speed"]); // "160" console.log(car["min speed"]); // "0"
  23. 23. Destructuring Assignment
  24. 24. Destructuring Assignment • Destructuring allows you to pattern match against array and objects • It extracts specific values to the individual local variables
  25. 25. // ES6 // Array matching var [a, , b] = [1,2,3]; console.log(a, b); // => 1 3 // Swapping using array [b, a] = [b, a]; console.log(b, a); // => 3 1 // Object Matching var {emacsUser, atomUser, vimUser } = getEditorUserInfo(); function getEditorUserInfo(){ return { vimUser: 'Tim', emacsUser: 'Sam', atomUser: 'Chris' }; } console.log(emacsUser); // => 'Sam' console.log(vimUser); // => 'Tim' console.log(atomUser); // => 'Chris'
  26. 26. // ES6 // Object Deep Matching var { user: { fN: firstName, lN: lastName } } = getUserInfo(); function getUserInfo(){ var user = { user: { fN: 'Adam', lN: 'Collins'} } return user; } console.log(firstName); // 'Adam' console.log(lastName); // 'Collins'
  27. 27. Default + Rest + Spread
  28. 28. Default + Rest + Spread • Using these features we can handle function’s parameters
  29. 29. Default
  30. 30. // ES5 function dailyWorkIncome(workHours, hourlyRate, bonus) { hourlyRate = hourlyRate || 25; bonus = bonus || 0 return (workHours * hourlyRate) + bonus; } dailyWorkIncome(7, 30); // 175 // ES6 function dailyWorkIncome(workHours, hourlyRate = 25, bonus = 0) { return (workHours * hourlyRate) + bonus; } dailyWorkIncome(7); // 175 dailyWorkIncome(7, 30); // 210 dailyWorkIncome(7, 30, 15); // 225
  31. 31. Rest
  32. 32. //ES6 function userNames(mainName, ...socialNames) { var allNames = []; allNames.push(mainName); for (let i of socialNames) { allNames.push(i); } return allNames; } userNames('MyName', 'TwitterName', 'GithubName'); // ["MyName","TwitterName","GithubName"]
  33. 33. Spread
  34. 34. // ES6 function f(a, b, c) { return a * b * c; } var values = [2,4,6,7]; f(...values); // 48
  35. 35. Loops & Generators
  36. 36. Loops //ES5 // Using forEeach on an array. ['John', 'Smith'].forEach(function(item){ console.log(item); }); // Using for-in for object var obj = { name: 'Hulk', color: 'green' } for(var k in obj) { console.log(obj[k]); }
  37. 37. Loops //ES6 // Using for-of for an array for(let item of ['John', 'Smith']){ console.log(item); } // Using for-of for an object var obj = { name: 'Hulk', color: 'green' } for(let k of Object.keys(obj)) { console.log(obj[k]); }
  38. 38. Generators • Generator is function which has multiple return points • Allows you to “pause & resume” a function • Interruptible Computations • Shallow Coroutines • Great for simplifying asynchronous code
  39. 39. function* numbers(){ var n = 1; var a; while(n < 3) { a = yield n++; console.log('a:', a); } }; var gen = numbers(); console.log(gen.next()); console.log(gen.next(2)); console.log(gen.next("three")); // {"value":1,"done":false} // a: 2 // {"value":2,"done":false} // a: three // {"done":true}
  40. 40. function* numbers(){ var n = 1; var a; while(true) { yield n++; } }; for (var n of numbers()) { if (n > 50) break; console.log(n); } // output: // 1 // 2 // 3 // . // . // . // 50
  41. 41. Map + Set
  42. 42. Map + Set • Efficient data structure for common algorithms • These provide methods likes ‘entries()’, ‘values()’ & ‘keys()’
  43. 43. // Map var m = new Map(); m.set("name", 'John'); var s = new Set(); s.add('Apple').add('Banana'); m.set('fruits', s); for(let entry of m.entries()){ console.log(entry); }; // ["name","John"] // ["fruits",["Apple","Banana"]] for(let entry of m.keys()){ console.log(entry); }; // name // fruits for(let entry of m.values()){ console.log(entry); }; // John // ["Apple","Banana"]
  44. 44. // Set var s = new Set(); s.add('Apple').add('Banana').add('Apple'); console.log(s.size === 2); // true console.log(s.has('Apple') === true); // true for(let entry of s.entries()){ console.log(entry); }; // ["Apple","Apple"] // ["Banana","Banana"] for(let entry of s.keys()){ console.log(entry); }; // Apple // Banana for(let entry of s.values()){ console.log(entry); }; // Apple // Banana
  45. 45. Arrows
  46. 46. Arrows • One of the cool features of ES6 • Arrow function has shorter syntax “=>” syntax compared to regular function • Unlike functions, arrows bind the “this” value as their surrounding code • Arrow functions are always anonymous functions • It throws the error when we use it with “new”
  47. 47. // ES5 var sum = function(num1, num2) { return num1 + num2; }; var evens = [2,4,6,8]; var odds = evens.map(function(v){ return v + 1; }); // ES6 var sum = (num1, num2) => num1 + num2; var evens = [2,4,6,8]; var odds = evens.map(v => v + 1);
  48. 48. //ES5 var name = 'Tom'; var obj = { name: 'Jerry', sayName: function(){ console.log(this.name); }, greet: function(){ setTimeout(function(){ console.log('Hi,' + this.name ); },100); } }; obj.sayName(); // logs Jerry obj.greet(); // logs Hi, Tom
  49. 49. //ES6 var name = 'Tom'; var obj = { name: 'Jerry', sayName: function(){ console.log(this.name); }, greet: function(){ setTimeout( ()=> { console.log('Hi,' + this.name ); },100); } }; obj.sayName(); // logs Jerry obj.greet(); // logs Hi, Jerry
  50. 50. Modules
  51. 51. Modules // lib/math.js export const pi = 3.141593; export function double(x){ return x + x; } // app.js import * at math from "lib/math"; console.log(math.pi); // 3.141593 console.log(math.double(10)); // 20 // other_app.js import {pi, double} from "lib/math"; console.log(pi); // 3.141593 console.log(double(10)); // 20
  52. 52. Classes
  53. 53. Classes • ES6 classes are syntactical sugar over JavaScript's existing prototype-based inheritance
  54. 54. // ES5 function Car(name) { this.name = name; } Car.prototype.getName = function() { console.log(this.name); }; let car = new Car("Mustang GT500"); car.getName(); // "Mustang GT500" console.log(car instanceof Car); // true console.log(car instanceof Object); // true
  55. 55. // ES6 class Car { // equivalent of the PersonType constructor constructor(name) { this.name = name; } // equivalent of PersonType.prototype.sayName sayName() { console.log(this.name); } } let car = new Car("Mustang GT500"); car.sayName(); // outputs "Mustang GT500" console.log(car instanceof Car); // true console.log(car instanceof Object); // true
  56. 56. ES6 setup on Rails
  57. 57. ES6 setup on Rails • Work in progress in Sprockets 4.x • Still, we can use sprockets-es6 gem • sprockets-es6 gem uses babel gem internally to transpile your ES6 file to ES5 • Another way using Node.js and Gulp
  58. 58. ES6 setup on Rails In your Gemfile, add these gems, • gem 'sprockets', ‘>=3.0.0.beta' • gem ‘sprockets-es6’ Run bundle install. Write down your ES6 code in files using .es extension and thats it :)
  59. 59. Thanks

×