ES6: Features + Rails

S
Santosh WadghuleSoftware Developer at KQInfotech
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
1 of 60

Recommended

ES2015 (ES6) Overview by
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overviewhesher
22.4K views102 slides
Explaining ES6: JavaScript History and What is to Come by
Explaining ES6: JavaScript History and What is to ComeExplaining ES6: JavaScript History and What is to Come
Explaining ES6: JavaScript History and What is to ComeCory Forsyth
1.7K views50 slides
An Intro To ES6 by
An Intro To ES6An Intro To ES6
An Intro To ES6FITC
1.6K views107 slides
EcmaScript 6 - The future is here by
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
4.8K views75 slides
ECMAScript 6 by
ECMAScript 6ECMAScript 6
ECMAScript 6Piotr Lewandowski
1K views42 slides
ES6 - Next Generation Javascript by
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation JavascriptRamesh Nair
12.3K views147 slides

More Related Content

What's hot

ES6 in Real Life by
ES6 in Real LifeES6 in Real Life
ES6 in Real LifeDomenic Denicola
5.5K views21 slides
Introduction into ES6 JavaScript. by
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
1.7K views43 slides
EcmaScript 6 by
EcmaScript 6 EcmaScript 6
EcmaScript 6 Manoj Kumar
1.7K views118 slides
ES6 PPT FOR 2016 by
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016Manoj Kumar
2.8K views129 slides
ES6: The Awesome Parts by
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome PartsDomenic Denicola
59.8K views41 slides
JavaScript ES6 by
JavaScript ES6JavaScript ES6
JavaScript ES6Leo Hernandez
1.4K views23 slides

What's hot(20)

Introduction into ES6 JavaScript. by boyney123
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
boyney1231.7K views
EcmaScript 6 by Manoj Kumar
EcmaScript 6 EcmaScript 6
EcmaScript 6
Manoj Kumar1.7K views
ES6 PPT FOR 2016 by Manoj Kumar
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
Manoj Kumar2.8K views
Javascript ES6 generators by Ramesh Nair
Javascript ES6 generatorsJavascript ES6 generators
Javascript ES6 generators
Ramesh Nair4.4K views
Command Line Applications in Ruby, 2018-05-08 by Keith Bennett
Command Line Applications in Ruby, 2018-05-08Command Line Applications in Ruby, 2018-05-08
Command Line Applications in Ruby, 2018-05-08
Keith Bennett75 views
ECMAScript 6 new features by GephenSG
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
GephenSG646 views
ECMAScript 6: A Better JavaScript for the Ambient Computing Era by Allen Wirfs-Brock
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-Brock14K views
FalsyValues. Dmitry Soshnikov - ECMAScript 6 by Dmitry Soshnikov
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov30.5K views
Minimizing Decision Fatigue to Improve Team Productivity by Derek Lee Boire
Minimizing Decision Fatigue to Improve Team ProductivityMinimizing Decision Fatigue to Improve Team Productivity
Minimizing Decision Fatigue to Improve Team Productivity
Derek Lee Boire1.9K views
AST Rewriting Using recast and esprima by Stephen Vance
AST Rewriting Using recast and esprimaAST Rewriting Using recast and esprima
AST Rewriting Using recast and esprima
Stephen Vance1.5K views
Javascript development done right by Pawel Szulc
Javascript development done rightJavascript development done right
Javascript development done right
Pawel Szulc1.6K views

Viewers also liked

Javascript Best Practice by
Javascript Best Practice Javascript Best Practice
Javascript Best Practice Naing Lin Aung
840 views19 slides
Intro to ES6 and why should you bother ! by
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
550 views14 slides
Short intro to ES6 Features by
Short intro to ES6 FeaturesShort intro to ES6 Features
Short intro to ES6 FeaturesNaing Lin Aung
679 views20 slides
Javascript and Jquery Best practices by
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
1.2K views23 slides
Intro to ES6 / ES2015 by
Intro to ES6 / ES2015Intro to ES6 / ES2015
Intro to ES6 / ES2015Jamal Sinclair O'Garro
565 views29 slides
10 Useful New Features of ECMA Script 6 by
10 Useful New Features of ECMA Script 610 Useful New Features of ECMA Script 6
10 Useful New Features of ECMA Script 6Lohith Goudagere Nagaraj
762 views19 slides

Viewers also liked(8)

Similar to ES6: Features + Rails

Node Boot Camp by
Node Boot CampNode Boot Camp
Node Boot CampTroy Miles
871 views102 slides
Es6 to es5 by
Es6 to es5Es6 to es5
Es6 to es5Shakhzod Tojiyev
289 views43 slides
Idiomatic Javascript (ES5 to ES2015+) by
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)David Atchley
336 views43 slides
React Native Evening by
React Native EveningReact Native Evening
React Native EveningTroy Miles
542 views76 slides
Workshop 10: ECMAScript 6 by
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Visual Engineering
697 views49 slides
ES6 is Nigh by
ES6 is NighES6 is Nigh
ES6 is NighDomenic Denicola
8K views56 slides

Similar to ES6: Features + Rails(20)

Node Boot Camp by Troy Miles
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles871 views
Idiomatic Javascript (ES5 to ES2015+) by David Atchley
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley336 views
React Native Evening by Troy Miles
React Native EveningReact Native Evening
React Native Evening
Troy Miles542 views
Introduction to ES6 with Tommy Cresine by Movel
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
Movel597 views
Game Design and Development Workshop Day 1 by Troy Miles
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles494 views
ECMAScript2015 by qmmr
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr217 views
Adding ES6 to Your Developer Toolbox by Jeff Strauss
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss541 views
JavaScript 2016 for C# Developers by Rick Beerendonk
JavaScript 2016 for C# DevelopersJavaScript 2016 for C# Developers
JavaScript 2016 for C# Developers
Rick Beerendonk563 views
Intro to React by Troy Miles
Intro to ReactIntro to React
Intro to React
Troy Miles922 views
ECMAScript 6 Review by Sperasoft
ECMAScript 6 ReviewECMAScript 6 Review
ECMAScript 6 Review
Sperasoft1.5K views

Recently uploaded

GigaIO: The March of Composability Onward to Memory with CXL by
GigaIO: The March of Composability Onward to Memory with CXLGigaIO: The March of Composability Onward to Memory with CXL
GigaIO: The March of Composability Onward to Memory with CXLCXL Forum
126 views12 slides
Throughput by
ThroughputThroughput
ThroughputMoisés Armani Ramírez
32 views11 slides
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy by
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy
"Role of a CTO in software outsourcing company", Yuriy NakonechnyyFwdays
40 views21 slides
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... by
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...NUS-ISS
28 views35 slides
Tunable Laser (1).pptx by
Tunable Laser (1).pptxTunable Laser (1).pptx
Tunable Laser (1).pptxHajira Mahmood
21 views37 slides
The Importance of Cybersecurity for Digital Transformation by
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital TransformationNUS-ISS
25 views26 slides

Recently uploaded(20)

GigaIO: The March of Composability Onward to Memory with CXL by CXL Forum
GigaIO: The March of Composability Onward to Memory with CXLGigaIO: The March of Composability Onward to Memory with CXL
GigaIO: The March of Composability Onward to Memory with CXL
CXL Forum126 views
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy by Fwdays
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy
"Role of a CTO in software outsourcing company", Yuriy Nakonechnyy
Fwdays40 views
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum... by NUS-ISS
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
Beyond the Hype: What Generative AI Means for the Future of Work - Damien Cum...
NUS-ISS28 views
The Importance of Cybersecurity for Digital Transformation by NUS-ISS
The Importance of Cybersecurity for Digital TransformationThe Importance of Cybersecurity for Digital Transformation
The Importance of Cybersecurity for Digital Transformation
NUS-ISS25 views
Liqid: Composable CXL Preview by CXL Forum
Liqid: Composable CXL PreviewLiqid: Composable CXL Preview
Liqid: Composable CXL Preview
CXL Forum121 views
.conf Go 2023 - Data analysis as a routine by Splunk
.conf Go 2023 - Data analysis as a routine.conf Go 2023 - Data analysis as a routine
.conf Go 2023 - Data analysis as a routine
Splunk90 views
MemVerge: Past Present and Future of CXL by CXL Forum
MemVerge: Past Present and Future of CXLMemVerge: Past Present and Future of CXL
MemVerge: Past Present and Future of CXL
CXL Forum110 views
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur by Fwdays
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur
"Thriving Culture in a Product Company — Practical Story", Volodymyr Tsukur
Fwdays40 views
Understanding GenAI/LLM and What is Google Offering - Felix Goh by NUS-ISS
Understanding GenAI/LLM and What is Google Offering - Felix GohUnderstanding GenAI/LLM and What is Google Offering - Felix Goh
Understanding GenAI/LLM and What is Google Offering - Felix Goh
NUS-ISS39 views
Transcript: The Details of Description Techniques tips and tangents on altern... by BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada119 views
Future of Learning - Khoong Chan Meng by NUS-ISS
Future of Learning - Khoong Chan MengFuture of Learning - Khoong Chan Meng
Future of Learning - Khoong Chan Meng
NUS-ISS31 views
Data-centric AI and the convergence of data and model engineering: opportunit... by Paolo Missier
Data-centric AI and the convergence of data and model engineering:opportunit...Data-centric AI and the convergence of data and model engineering:opportunit...
Data-centric AI and the convergence of data and model engineering: opportunit...
Paolo Missier29 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada110 views
Empathic Computing: Delivering the Potential of the Metaverse by Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst449 views
AMD: 4th Generation EPYC CXL Demo by CXL Forum
AMD: 4th Generation EPYC CXL DemoAMD: 4th Generation EPYC CXL Demo
AMD: 4th Generation EPYC CXL Demo
CXL Forum126 views
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor... by Vadym Kazulkin
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
How to reduce cold starts for Java Serverless applications in AWS at JCON Wor...
Vadym Kazulkin70 views
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa... by The Digital Insurer
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...
Webinar : Competing for tomorrow’s leaders – How MENA insurers can win the wa...

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

  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.