SlideShare ist ein Scribd-Unternehmen logo
1 von 60
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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie ES6: Features + Rails

ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
qmmr
 

Ähnlich wie 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?
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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 :)

Hinweis der Redaktion

  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.