SlideShare a Scribd company logo
ES6Features & Rails
Santosh Wadghule
@mechanicles
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

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
Domenic Denicola
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney123
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
Domenic Denicola
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
Leo Hernandez
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
Domenic Denicola
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
Bruno Scopelliti
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
Kevin Langley Jr.
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
Ramesh Nair
 
Command Line Applications in Ruby, 2018-05-08
Command Line Applications in Ruby, 2018-05-08Command Line Applications in Ruby, 2018-05-08
Command Line Applications in Ruby, 2018-05-08
Keith Bennett
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
GephenSG
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
Allen Wirfs-Brock
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6
Workhorse Computing
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee Boire
 
Javascript the New Parts v2
Javascript the New Parts v2Javascript the New Parts v2
Javascript the New Parts v2
Federico Galassi
 
AST Rewriting Using recast and esprima
AST Rewriting Using recast and esprimaAST Rewriting Using recast and esprima
AST Rewriting Using recast and esprima
Stephen Vance
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
Pawel Szulc
 

What's hot (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Javascript ES6 generators
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
 
Command Line Applications in Ruby, 2018-05-08
Command Line Applications in Ruby, 2018-05-08Command Line Applications in Ruby, 2018-05-08
Command Line Applications in Ruby, 2018-05-08
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6Ethiopian multiplication in Perl6
Ethiopian multiplication in Perl6
 
Minimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
 
Javascript the New Parts v2
Javascript the New Parts v2Javascript the New Parts v2
Javascript the New Parts v2
 
Ruby 1.9
Ruby 1.9Ruby 1.9
Ruby 1.9
 
AST Rewriting Using recast and esprima
AST Rewriting Using recast and esprimaAST Rewriting Using recast and esprima
AST Rewriting Using recast and esprima
 
Javascript development done right
Javascript development done rightJavascript development done right
Javascript development done right
 

Viewers also liked

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

Viewers also liked (8)

Javascript Best Practice
Javascript Best Practice Javascript Best Practice
Javascript Best Practice
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
Short intro to ES6 Features
Short intro to ES6 FeaturesShort intro to ES6 Features
Short intro to ES6 Features
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Intro to ES6 / ES2015
Intro to ES6 / ES2015Intro to ES6 / ES2015
Intro to ES6 / ES2015
 
10 Useful New Features of ECMA Script 6
10 Useful New Features of ECMA Script 610 Useful New Features of ECMA Script 6
10 Useful New Features of ECMA Script 6
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 

Similar to ES6: Features + Rails

Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
Shakhzod Tojiyev
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
Binary Studio
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
Movel
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015qmmr
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
Justin Alexander
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
Sebastiano Armeli
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
Miguel Ruiz Rodriguez
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
Sperasoft
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
The Software House
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
James Ford
 

Similar to ES6: Features + Rails (20)

Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
Academy PRO: ES2015
Academy PRO: ES2015Academy PRO: ES2015
Academy PRO: ES2015
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
ES6: The future is now
ES6: The future is nowES6: The future is now
ES6: The future is now
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
 
JavaScript 2016 for C# Developers
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
 
Internal workshop es6_2015
Internal workshop es6_2015Internal workshop es6_2015
Internal workshop es6_2015
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
ECMAScript 6 Review
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
ES6, WTF?
ES6, WTF?ES6, WTF?
ES6, WTF?
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

ES6: Features + Rails

  • 1. ES6Features & Rails Santosh Wadghule @mechanicles
  • 2.
  • 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

  1. 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.
  2. Today I’m going to cover.
  3. Anybody knows?
  4. 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.
  5. 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.
  6. In ES5, variables either function scoped or global scoped.
  7. 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’.
  8. 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.
  9. ES5, duplicated property and duplicated local variable name.
  10. This is called as concise method syntax.
  11. One of the best features of ES6. It definitely will improve the productivity of JavaScript developers
  12. Array matching and Swapping using array, These concepts are taken from CoffeeScript.
  13. firstName and lastName local variables are specified using object literal syntax
  14. JavaScript function had not changed much since the language was first introduced
  15. Rest Parameters. It allows to represent an indefinite number of arguments as an array.
  16. Generator definitely will be a game changer in Javascript.
  17. Example of lazy evaluation.
  18. In JavaScript, we trite a lot function keyword for declaring regular named functions, declaring anonymous functions or callback functions.
  19. Until arrows functions, every new function defined its own this value. Here this is bound to the global object, not the obj.