SlideShare a Scribd company logo
ES6Features & Rails
Santosh Wadghule
@mechanicles
ES6: Features + Rails
ES6 + Its Features +
Setup on Rails
ES6? What is it?
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.
ES6 Features
ES6 Features
• Let + Const
• Template string
• Destructuring Assignment
• Default + Rest + Spread
• Loops, Generators
• Enhanced object literals
• Map + Set
• Arrows
• Modules
• Classes
Let + Const
Let + Const
• Variables before ES6 are function scoped
• ‘let’ & ‘const’ are block-scoped binding constructs
• ‘let’ is the new variable
• ‘const’ is single-assignment.
Let
// 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();
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();
Const
// 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();
// 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
Template Strings
Template Strings
• A new way of string interpolation
• It adds syntactic sugar for constructing strings
• Easy to handle multiline strings
// 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?
Enhanced Object Literals
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
Property Initializer Shorthand
// ES5
function createPost(title, content) {
return {
title: title,
content: content
};
}
//ES6
function createPost(title, content) {
return {
title,
content
};
}
Method Initializer Shorthand
// ES5
var car = {
name: "Mustang GT500",
startEngine: function() {
console.log('starting...');
}
};
//ES6
var car = {
name: "Mustang GT500",
startEngine(){
console.log('starting...');
}
};
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"
Destructuring Assignment
Destructuring Assignment
• Destructuring allows you to pattern match against
array and objects
• It extracts specific values to the individual local
variables
// 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'
// 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'
Default + Rest + Spread
Default + Rest + Spread
• Using these features we can handle function’s
parameters
Default
// 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
Rest
//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"]
Spread
// ES6
function f(a, b, c) {
return a * b * c;
}
var values = [2,4,6,7];
f(...values); // 48
Loops & Generators
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]);
}
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]);
}
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
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}
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
Map + Set
Map + Set
• Efficient data structure for common algorithms
• These provide methods likes ‘entries()’, ‘values()’ &
‘keys()’
// 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"]
// 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
Arrows
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”
// 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);
//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
//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
Modules
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
Classes
Classes
• ES6 classes are syntactical sugar over JavaScript's
existing prototype-based inheritance
// 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
// 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
ES6 setup on Rails
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
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 :)
Thanks

More Related Content

What's hot (20)

PPTX
ES6 in Real Life
Domenic Denicola
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
ODP
EcmaScript 6
Manoj Kumar
 
ODP
ES6 PPT FOR 2016
Manoj Kumar
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PDF
JavaScript ES6
Leo Hernandez
 
PPTX
Async Frontiers
Domenic Denicola
 
PPTX
ES6 Overview
Bruno Scopelliti
 
PPTX
Modern JS with ES6
Kevin Langley Jr.
 
PDF
Javascript ES6 generators
RameshNair6
 
PDF
Command Line Applications in Ruby, 2018-05-08
Keith Bennett
 
PDF
ECMAScript 6 new features
GephenSG
 
PPT
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
PDF
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
PDF
Ethiopian multiplication in Perl6
Workhorse Computing
 
PDF
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
PDF
Javascript the New Parts v2
Federico Galassi
 
PDF
Ruby 1.9
Wen-Tien Chang
 
PDF
AST Rewriting Using recast and esprima
Stephen Vance
 
PDF
Javascript development done right
Pawel Szulc
 
ES6 in Real Life
Domenic Denicola
 
Introduction into ES6 JavaScript.
boyney123
 
EcmaScript 6
Manoj Kumar
 
ES6 PPT FOR 2016
Manoj Kumar
 
ES6: The Awesome Parts
Domenic Denicola
 
JavaScript ES6
Leo Hernandez
 
Async Frontiers
Domenic Denicola
 
ES6 Overview
Bruno Scopelliti
 
Modern JS with ES6
Kevin Langley Jr.
 
Javascript ES6 generators
RameshNair6
 
Command Line Applications in Ruby, 2018-05-08
Keith Bennett
 
ECMAScript 6 new features
GephenSG
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Ethiopian multiplication in Perl6
Workhorse Computing
 
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee
 
Javascript the New Parts v2
Federico Galassi
 
Ruby 1.9
Wen-Tien Chang
 
AST Rewriting Using recast and esprima
Stephen Vance
 
Javascript development done right
Pawel Szulc
 

Viewers also liked (8)

PDF
Javascript Best Practice
Naing Lin Aung
 
PPTX
Intro to ES6 and why should you bother !
Gaurav Behere
 
PDF
Short intro to ES6 Features
Naing Lin Aung
 
PPT
Javascript and Jquery Best practices
Sultan Khan
 
PDF
Intro to ES6 / ES2015
Jamal Sinclair O'Garro
 
PPTX
10 Useful New Features of ECMA Script 6
Lohith Goudagere Nagaraj
 
PDF
Intro to testing Javascript with jasmine
Timothy Oxley
 
ODP
Object-Oriented Javascript
Iban Martinez
 
Javascript Best Practice
Naing Lin Aung
 
Intro to ES6 and why should you bother !
Gaurav Behere
 
Short intro to ES6 Features
Naing Lin Aung
 
Javascript and Jquery Best practices
Sultan Khan
 
Intro to ES6 / ES2015
Jamal Sinclair O'Garro
 
10 Useful New Features of ECMA Script 6
Lohith Goudagere Nagaraj
 
Intro to testing Javascript with jasmine
Timothy Oxley
 
Object-Oriented Javascript
Iban Martinez
 
Ad

Similar to ES6: Features + Rails (20)

PDF
Node Boot Camp
Troy Miles
 
PDF
Es6 to es5
Shakhzod Tojiyev
 
PDF
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
PDF
React Native Evening
Troy Miles
 
PDF
Workshop 10: ECMAScript 6
Visual Engineering
 
PPTX
ES6 is Nigh
Domenic Denicola
 
PPTX
Academy PRO: ES2015
Binary Studio
 
PDF
Game Design and Development Workshop Day 1
Troy Miles
 
PDF
ECMAScript2015
qmmr
 
PPTX
Es6 hackathon
Justin Alexander
 
PDF
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
PDF
ES6: The future is now
Sebastiano Armeli
 
PDF
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
PDF
JavaScript 2016 for C# Developers
Rick Beerendonk
 
PDF
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
PDF
Intro to React
Troy Miles
 
PDF
ECMAScript 6 Review
Sperasoft
 
PDF
"let ECMAScript = 6"
The Software House
 
PDF
ES6, WTF?
James Ford
 
PDF
Javascript basics
Fin Chen
 
Node Boot Camp
Troy Miles
 
Es6 to es5
Shakhzod Tojiyev
 
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
React Native Evening
Troy Miles
 
Workshop 10: ECMAScript 6
Visual Engineering
 
ES6 is Nigh
Domenic Denicola
 
Academy PRO: ES2015
Binary Studio
 
Game Design and Development Workshop Day 1
Troy Miles
 
ECMAScript2015
qmmr
 
Es6 hackathon
Justin Alexander
 
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
ES6: The future is now
Sebastiano Armeli
 
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
JavaScript 2016 for C# Developers
Rick Beerendonk
 
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
Intro to React
Troy Miles
 
ECMAScript 6 Review
Sperasoft
 
"let ECMAScript = 6"
The Software House
 
ES6, WTF?
James Ford
 
Javascript basics
Fin Chen
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Digital Circuits, important subject in CS
contactparinay1
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 

ES6: Features + Rails

  • 1. ES6Features & Rails Santosh Wadghule @mechanicles
  • 3. ES6 + Its Features + Setup on Rails
  • 5. 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.
  • 7. ES6 Features • Let + Const • Template string • Destructuring Assignment • Default + Rest + Spread • Loops, Generators • Enhanced object literals • Map + Set • Arrows • Modules • Classes
  • 9. Let + Const • Variables before ES6 are function scoped • ‘let’ & ‘const’ are block-scoped binding constructs • ‘let’ is the new variable • ‘const’ is single-assignment.
  • 10. Let
  • 11. // 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();
  • 12. 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();
  • 13. Const
  • 14. // 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();
  • 15. // 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
  • 17. Template Strings • A new way of string interpolation • It adds syntactic sugar for constructing strings • Easy to handle multiline strings
  • 18. // 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?
  • 20. 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
  • 21. Property Initializer Shorthand // ES5 function createPost(title, content) { return { title: title, content: content }; } //ES6 function createPost(title, content) { return { title, content }; }
  • 22. Method Initializer Shorthand // ES5 var car = { name: "Mustang GT500", startEngine: function() { console.log('starting...'); } }; //ES6 var car = { name: "Mustang GT500", startEngine(){ console.log('starting...'); } };
  • 23. 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"
  • 25. Destructuring Assignment • Destructuring allows you to pattern match against array and objects • It extracts specific values to the individual local variables
  • 26. // 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'
  • 27. // 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'
  • 28. Default + Rest + Spread
  • 29. Default + Rest + Spread • Using these features we can handle function’s parameters
  • 31. // 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
  • 32. Rest
  • 33. //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"]
  • 35. // ES6 function f(a, b, c) { return a * b * c; } var values = [2,4,6,7]; f(...values); // 48
  • 37. 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]); }
  • 38. 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]); }
  • 39. 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
  • 40. 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}
  • 41. 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
  • 43. Map + Set • Efficient data structure for common algorithms • These provide methods likes ‘entries()’, ‘values()’ & ‘keys()’
  • 44. // 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"]
  • 45. // 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
  • 47. 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”
  • 48. // 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);
  • 49. //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
  • 50. //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
  • 52. 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
  • 54. Classes • ES6 classes are syntactical sugar over JavaScript's existing prototype-based inheritance
  • 55. // 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
  • 56. // 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
  • 57. ES6 setup on Rails
  • 58. 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
  • 59. 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 :)

Editor's Notes

  • #3: I work at BigBinary. It’s Ruby on Rails development company. We also do have some good tutorials for JavaScript, ReactJs and Rails. So do check it out.
  • #4: Today I’m going to cover.
  • #5: Anybody knows?
  • #6: In 1995, JavaScript was released(1 stable version), at that time Java was so popular. These JavaScript guys used this Java name to make popular for marketing kind of purpose. But we all love JavaScript. But not for Java :). I’m just Kidding. ES6 had started in 2011, they planed to release first stable version in June 2015.
  • #8: Here I have included some of its features which I felt more promising. There are also some new features but I haven’t included here.
  • #12: In ES5, variables either function scoped or global scoped.
  • #15: In ES5, We define constant using capital letters then we assign to value. But that is not a actual Constant, because can not prevent it from being changed. It’s only convention that we should not change it the program. But ES6 includes new way to declare constants by using ‘const’ instead of using ‘var’.
  • #21: What is object literal? It compound value where we can set properties and that property can hold their own values of any type. It is strongest part of JavaScript. Because of this we can implemented module pattern in the JavaScript very easily.
  • #22: ES5, duplicated property and duplicated local variable name.
  • #23: This is called as concise method syntax.
  • #26: One of the best features of ES6. It definitely will improve the productivity of JavaScript developers
  • #27: Array matching and Swapping using array, These concepts are taken from CoffeeScript.
  • #28: firstName and lastName local variables are specified using object literal syntax
  • #30: JavaScript function had not changed much since the language was first introduced
  • #33: Rest Parameters. It allows to represent an indefinite number of arguments as an array.
  • #40: Generator definitely will be a game changer in Javascript.
  • #42: Example of lazy evaluation.
  • #48: In JavaScript, we trite a lot function keyword for declaring regular named functions, declaring anonymous functions or callback functions.
  • #50: Until arrows functions, every new function defined its own this value. Here this is bound to the global object, not the obj.