SlideShare a Scribd company logo
#GAPAND2015
proudly present…
and
EcmaScript unchained
EcmaScript unchained
EcmaScript unchained
Please don’t talk
while the show is
going on.
Just sit down, eat
popcorns and do
not interrupt.
Thanks.
Interrupt me. Ask
any question you
have (no
answered
guaranteed :P)
Let’s enjoy
together!
EcmaScript 2015 top new features
EcmaScript unchained
function foo() {
console.log(varidx); // Prints undefined as varidx is hoisted
for (var varidx = 0; varidx < 10; varidx++) {; }
console.log(varidx); // Prints 10
varidx = 100;
}
function foolet() {
console.log(letidx); // Reference error
for (let letidx = 0; letidx < 10; letidx++) {; }
console.log(letidx); // Reference error
letidx = 100;
}
function fooconst() {
console.log(max); // Error (access to const before
is initialized)
const max = 10;
max = 0; // Syntax error!
}
EcmaScript unchained
var Brewery = function(name) {
this.name = name;
this.beers = [
{name: "Punk IPA", style:"ipa"},
{name: "5 am", style: "pale ale"},
{name: "Tokio", style: "stout"}];
this.beersByType = function(type) {
return this.beers.filter(function (element) {
return element.style == type;
});
}
this.getBeersWithFullName = function() {
return this.beers.map(function(element) {
return {
name: element.name + " by " + this.name,
style: element.style};
});
}
}
Classic (ES5) code. Very verbose syntax
The new arrow syntax
var Brewery = function(name) {
this.name = name;
this.beers = [
{name: "Punk IPA", style:"ipa"},
{name: "5 am", style: "pale ale"},
{name: "Tokio", style: "stout"}];
this.beersByType = function(type) {
return this.beers.filter(e => e.syle == type);
}
this.getBeersWithFullName = function() {
return this.beers.map(function(element) {
return {
name: element.name + " by " + this.name,
style: element.style};
});
}
}
this problem. What is the value of
this inside the inner function?
this.getBeersWithFullName = function () {
var self = this;
return this.beers.map(function (element) {
return {
name: element.name + " by " + self.name,
style: element.style};
});
}
Need to remember use the “self”
variable instead of “this” in the
inner function.
Unnatural way to do things.
this.getBeersWithFullName = function () {
return this.beers.map(function (element) {
return {
name: element.name + " by " + this.name,
style: element.style
};
}.bind(this));
}
Just need to call bind in the inner
function to tie it to the previous
this context.
More elegant than using self, but
still unnatural...
Arrow functions do what ES
should be done from the
beginning: preserve the “this”
context.
this.getBeersWithFullName = function () {
return this.beers.map(e => ({
name: e.name + " by " + this.name,
style: e.style
}));
}
Arrow functions do what ES
should be done from the
beginning: preserve the “this”
context.
this.getBeersWithFullName = function () {
return this.beers.map(e => ({
name: e.name + " by " + this.name,
style: e.style
}));
}
Bonus: Do you notice the parens?
ES parser needs them if arrow
function returns a object in
notation-object form.
EcmaScript unchained
ES5 Standard code, using string
concatenation to create the name
property
this.getBeersWithFullName = function () {
return this.beers.map(e => ({
name: e.name + " by " + this.name,
style: e.style
}));
}
ES2015 code with string
interpolation
this.getBeersWithFullName = function () {
return this.beers.map(e => ({
name: `${e.name} by ${this.name}`,
style: e.style
}));
}
Yes... We had two markers for strings in ES (single quotes and double quotes) but for string
interoplation we will use a new third marker.
Bonus: String interpolation works on multi-line strings. You can still use n if prefer, of course.
EcmaScript unchained
var question = 'The answer to life the universe and everything';
var answer = 42;
var base = {
question,
answer,
toString: (() => `${this.question} is ${this.answer}`)
};
var der = {
__proto__: base,
['answer_' + (() => this.answer)()]: this.answer
}
EcmaScript unchained
We can use strings for object
properties as usual
We can create a Symbol using
Symbol.for(“name”) or
Symbol(“name”)
And we can use this newly Symbol
to create a new property for the
object
var obj = {};
obj[Symbol("a")] = "a";
obj[Symbol.for("b")] = "b";
obj["c"] = "c";
obj.d = "d";
for (var i in obj) {
console.log(i); // logs "c" and "d"
}
But are not private! Welcome to
Object.getOwnPropertySymbols()
Properties stored in símbols don’t
appear in for..in iterations nor in
Object.getOwnPropertyNames()
Of course... No string coertion
exists on Symbols
Symbol("a") == Symbol("a") // false
Symbol("a") === Symbol("a") // false
Symbol("a") == Symbol("a") // true
Symbol.for("a") === Symbol.for("a") // true
Symbol("a") == "a" // false
Symbol.for("a") == "a" // false
EcmaScript unchained
Any sufficiently
advanced
programming
technique is
indistinguishable
from WTF
Sir Arthur C. Clarke
EcmaScript unchained
var values = [42, 69];
var x = 42;
var y = 69;
ES5 classic way of doing this
var values = [42, 69];
var [x,y] = values; Same with ES2015 destructuring
var x = 42;
var y = 69;
We want x = 69 and y = 42, but
with one simple line of code...
var x = 42;
var y = 69;
[x, y] = [y, x];
This declares three variables,
called c, d and e.
Value of c is first variable of arr (4)
Value of d is second variable of arr
(8)
Value of e is the rest values of arr
(an array with 15, 16, 23 and 42)
var arr = [4, 8, 15, 16, 23, 42];
var [c,d,...e ] = arr
function foo(name, options, ...other) {
// Some code
}
Inside foo:
name is value of 1st parameter (or undefined)
options is value of 2nd parameter (or undefined)
other is an array with all the others paràmetres (or
empty array but never undefined)
Just keep in mind that x.f(...a) is equivalent to f.apply(x, a);
Iterators and for..of
An iterator is a function with a
specific name [Symbol.iterator].
This function mush return an
object with one method next().
The method next() must return an
object with two properties:
value: corrent value of iteration
done: boolean that equals true if
the last element has been reached.
let fibonacci = {
[Symbol.iterator]() {
let pre = 0, cur = 1;
return {
next() {
[pre, cur] = [cur, pre + cur];
return { done: false, value: cur }
}
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
Notice the new for..of to iterate over all the values of
the iterator of an object
EcmaScript unchained
Use of function* to create the
generator.
Generators return iterators
([Symbol.iterator])
Use of yield to return “the next”
value of the iterator
If a generator never exits it returns
a “never ending” iterator. Of
course you must stop iterating it
when no more vàlues are needed.
var fibonacci = {
[Symbol.iterator]: function*() {
var pre = 0, cur = 1;
for (;;) {
var temp = pre;
pre = cur;
cur += temp;
yield cur;
}
}
}
for (var n of fibonacci) {
// truncate the sequence at 1000
if (n > 1000)
break;
console.log(n);
}
EcmaScript unchained
This is equivalent to the
constructor function pattern in
ES5
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
Objects must be created with new and classes do not exist in runtime (typeof
Point is ‘function’)
EcmaScript unchained
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
// More stuff
}
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
// more stuff
}
let cp = new ColorPoint(25, 8, 'green');
Modules
EcmaScript unchained
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
Any declaration prefixed by
“export” keyword is an export of
the module
Using import keyword we can
choose what of the exports of the
module we want to include to the
global namespace
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
Any declaration prefixed by
“export” keyword is an export of
the module
Using import keyword we can
choose what of the exports of the
module we want to include to the
global namespace
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
EcmaScript unchained
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
Any declaration prefixed by
“export” keyword is an export of
the module
You can, of course, specify a
namespace for the import,
keeping the global namespace
clean (at least all clean that the
w3c guys allow us :P)...
//------ main.js ------
import * as lib from 'lib';
console.log(lib.square(11)); // 121
console.log(lib.diag(4, 3)); // 5
Did you notice the use of * to import all the exports of a module?
Module exports a class (note the
use of default).
Default exports must be named
on import
Module export just a function
//------ MyClass.js ------
export default class { ... };
//------ main2.js ------
import MyClass from 'MyClass';
let inst = new MyClass();
//------ myFunc.js ------
export default function () { ... };
//------ main1.js ------
import myFunc from 'myFunc';
myFunc();
This is not allowed in ES6
Less flexibility but no need to execute the code to find the
imports or exports of a module. Can be optimized.
var mylib;
if (Math.random()) {
mylib = require('foo');
} else {
mylib = require('bar');
}
Eduard Tomàs i Avellana
#GAPAND2015
EcmaScript unchained

More Related Content

What's hot (20)

PDF
Introduction to Swift programming language.
Icalia Labs
 
PDF
The Vanishing Pattern: from iterators to generators in Python
OSCON Byrum
 
PDF
Imugi: Compiler made with Python
Han Lee
 
PDF
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes
 
PDF
An Intro To ES6
FITC
 
PDF
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
ODP
EcmaScript 6
Manoj Kumar
 
PDF
JavaScript - new features in ECMAScript 6
Solution4Future
 
PPTX
ES6 in Real Life
Domenic Denicola
 
PDF
ECMAScript 6 Review
Sperasoft
 
ODP
ES6 PPT FOR 2016
Manoj Kumar
 
PPTX
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
PPT
Developing iOS apps with Swift
New Generation Applications
 
PDF
Exploring ES6
Ximing Dai
 
PDF
Introduction into ES6 JavaScript.
boyney123
 
PPTX
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
PDF
PHP Performance Trivia
Nikita Popov
 
PDF
The Design of the Scalaz 8 Effect System
John De Goes
 
PDF
C++ L11-Polymorphism
Mohammad Shaker
 
PPTX
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 
Introduction to Swift programming language.
Icalia Labs
 
The Vanishing Pattern: from iterators to generators in Python
OSCON Byrum
 
Imugi: Compiler made with Python
Han Lee
 
Blazing Fast, Pure Effects without Monads — LambdaConf 2018
John De Goes
 
An Intro To ES6
FITC
 
"Немного о функциональном программирование в JavaScript" Алексей Коваленко
Fwdays
 
EcmaScript 6
Manoj Kumar
 
JavaScript - new features in ECMAScript 6
Solution4Future
 
ES6 in Real Life
Domenic Denicola
 
ECMAScript 6 Review
Sperasoft
 
ES6 PPT FOR 2016
Manoj Kumar
 
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
Developing iOS apps with Swift
New Generation Applications
 
Exploring ES6
Ximing Dai
 
Introduction into ES6 JavaScript.
boyney123
 
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
PHP Performance Trivia
Nikita Popov
 
The Design of the Scalaz 8 Effect System
John De Goes
 
C++ L11-Polymorphism
Mohammad Shaker
 
FParsec Hands On - F#unctional Londoners 2014
Phillip Trelford
 

Viewers also liked (20)

PPTX
Winobjc - Windows Bridge for iOS
Eduard Tomàs
 
PPTX
Introducción a ObjectiveC e IOS
Eduard Tomàs
 
PPTX
Aplicaciones Metro UI para Windows8 con C# y XAML (12 horas Visual Studio)
Eduard Tomàs
 
PPTX
Asp.Net vNext - La revolución que viene
Eduard Tomàs
 
PPTX
Microsoft Code Contracts
Eduard Tomàs
 
PPTX
Introducción a ReactJS
Eduard Tomàs
 
PPTX
JavaScript - HTML5 - IndexedDb
Eduard Tomàs
 
PPTX
Introducción al desarrollo de videojuegos 2D con Wave Engine
Eduard Tomàs
 
PPTX
React native - t3chfest 2016
Eduard Tomàs
 
PPTX
MongoDb (BcnDevCon Nov 2011)
Eduard Tomàs
 
PPTX
#netIO 1 - Ecosistema .NET
Eduard Tomàs
 
PPTX
Interfaces rest
Eduard Tomàs
 
PPTX
ASP.NET vNext... Desarrollo cross platform
Eduard Tomàs
 
PPTX
Handlebars
Eduard Tomàs
 
PPTX
Una tapa de ecmascript 6
Eduard Tomàs
 
PPTX
React native - Unleash the power of your device
Eduard Tomàs
 
PPTX
Vista aérea de los lenguajes de programación
Eduard Tomàs
 
PPTX
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs
 
PPTX
Async / Await: Programación asíncrona para dummies (12 horas visual studio)
Eduard Tomàs
 
PPTX
Novedades de ASP.NET MVC6
Eduard Tomàs
 
Winobjc - Windows Bridge for iOS
Eduard Tomàs
 
Introducción a ObjectiveC e IOS
Eduard Tomàs
 
Aplicaciones Metro UI para Windows8 con C# y XAML (12 horas Visual Studio)
Eduard Tomàs
 
Asp.Net vNext - La revolución que viene
Eduard Tomàs
 
Microsoft Code Contracts
Eduard Tomàs
 
Introducción a ReactJS
Eduard Tomàs
 
JavaScript - HTML5 - IndexedDb
Eduard Tomàs
 
Introducción al desarrollo de videojuegos 2D con Wave Engine
Eduard Tomàs
 
React native - t3chfest 2016
Eduard Tomàs
 
MongoDb (BcnDevCon Nov 2011)
Eduard Tomàs
 
#netIO 1 - Ecosistema .NET
Eduard Tomàs
 
Interfaces rest
Eduard Tomàs
 
ASP.NET vNext... Desarrollo cross platform
Eduard Tomàs
 
Handlebars
Eduard Tomàs
 
Una tapa de ecmascript 6
Eduard Tomàs
 
React native - Unleash the power of your device
Eduard Tomàs
 
Vista aérea de los lenguajes de programación
Eduard Tomàs
 
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs
 
Async / Await: Programación asíncrona para dummies (12 horas visual studio)
Eduard Tomàs
 
Novedades de ASP.NET MVC6
Eduard Tomàs
 
Ad

Similar to EcmaScript unchained (20)

PPT
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
PPT
SDC - Einführung in Scala
Christian Baranowski
 
PPTX
Things about Functional JavaScript
ChengHui Weng
 
PPTX
ES6 Overview
Bruno Scopelliti
 
PDF
JavaScript - Agora nervoso
Luis Vendrame
 
PDF
Introduction to Functional Programming with Scala
pramode_ce
 
PDF
Introduction to ES2015
kiranabburi
 
PPTX
Advanced JavaScript
Zsolt Mészárovics
 
PDF
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
PDF
Javascript
Vlad Ifrim
 
PPTX
Es6 hackathon
Justin Alexander
 
PPTX
ES6 is Nigh
Domenic Denicola
 
PDF
ES6: The Awesome Parts
Domenic Denicola
 
PPT
Scala - brief intro
Razvan Cojocaru
 
PDF
ECMAScript 6
WebF
 
PPT
Cpp tutorial
Vikas Sharma
 
PPTX
Introduction to kotlin
Shaul Rosenzwieg
 
PPT
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
PPTX
Javascript Basics
msemenistyi
 
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
TypeScript Introduction
Dmitry Sheiko
 
SDC - Einführung in Scala
Christian Baranowski
 
Things about Functional JavaScript
ChengHui Weng
 
ES6 Overview
Bruno Scopelliti
 
JavaScript - Agora nervoso
Luis Vendrame
 
Introduction to Functional Programming with Scala
pramode_ce
 
Introduction to ES2015
kiranabburi
 
Advanced JavaScript
Zsolt Mészárovics
 
Think Async: Asynchronous Patterns in NodeJS
Adam L Barrett
 
Javascript
Vlad Ifrim
 
Es6 hackathon
Justin Alexander
 
ES6 is Nigh
Domenic Denicola
 
ES6: The Awesome Parts
Domenic Denicola
 
Scala - brief intro
Razvan Cojocaru
 
ECMAScript 6
WebF
 
Cpp tutorial
Vikas Sharma
 
Introduction to kotlin
Shaul Rosenzwieg
 
Paradigmas de Linguagens de Programacao - Aula #4
Ismar Silveira
 
Javascript Basics
msemenistyi
 
Ad

More from Eduard Tomàs (20)

PPTX
Kubernetes: Do's, don'ts and why's
Eduard Tomàs
 
PPTX
KCDS 2021- Escalando workloads serverless en Kubernetes con KEDA
Eduard Tomàs
 
PPTX
Escalando workloads serverless en Kubernetes con Keda
Eduard Tomàs
 
PPTX
C#9 - Más C# que nunca
Eduard Tomàs
 
PPTX
CollabDays 2020 Barcelona - Serverless Kubernetes with KEDA
Eduard Tomàs
 
PPTX
Keda o como convertir Kubernetess en Serverless
Eduard Tomàs
 
PPTX
.NET Memoria y Rendimiento
Eduard Tomàs
 
PPTX
Containers en .NET (Dot Net 2018 - Spain)
Eduard Tomàs
 
PPTX
Esos contenedores, ¡a producción! (Commit Conf 2018)
Eduard Tomàs
 
PPTX
Codemotion 2015 - Bienvenido de nuevo c++
Eduard Tomàs
 
PPTX
El "peor" lenguaje del mundo
Eduard Tomàs
 
PPTX
Containerize a netcore application with aks
Eduard Tomàs
 
PPTX
Escenarios avanzados en AKS (Global Azure Bootcamp Barcelona 2019)
Eduard Tomàs
 
PPTX
Aplicaciones de consola fáciles? Más quisieramos
Eduard Tomàs
 
PPTX
Serverless with Azure Functions and CosmosDb
Eduard Tomàs
 
PPTX
Docker y todo eso... más o menos
Eduard Tomàs
 
PPTX
Microservices: Yes or not?
Eduard Tomàs
 
PPTX
ASP.NET MVC Core
Eduard Tomàs
 
PPTX
Azure functions
Eduard Tomàs
 
PPTX
Asp.Net Core 1.0 Deep Dive
Eduard Tomàs
 
Kubernetes: Do's, don'ts and why's
Eduard Tomàs
 
KCDS 2021- Escalando workloads serverless en Kubernetes con KEDA
Eduard Tomàs
 
Escalando workloads serverless en Kubernetes con Keda
Eduard Tomàs
 
C#9 - Más C# que nunca
Eduard Tomàs
 
CollabDays 2020 Barcelona - Serverless Kubernetes with KEDA
Eduard Tomàs
 
Keda o como convertir Kubernetess en Serverless
Eduard Tomàs
 
.NET Memoria y Rendimiento
Eduard Tomàs
 
Containers en .NET (Dot Net 2018 - Spain)
Eduard Tomàs
 
Esos contenedores, ¡a producción! (Commit Conf 2018)
Eduard Tomàs
 
Codemotion 2015 - Bienvenido de nuevo c++
Eduard Tomàs
 
El "peor" lenguaje del mundo
Eduard Tomàs
 
Containerize a netcore application with aks
Eduard Tomàs
 
Escenarios avanzados en AKS (Global Azure Bootcamp Barcelona 2019)
Eduard Tomàs
 
Aplicaciones de consola fáciles? Más quisieramos
Eduard Tomàs
 
Serverless with Azure Functions and CosmosDb
Eduard Tomàs
 
Docker y todo eso... más o menos
Eduard Tomàs
 
Microservices: Yes or not?
Eduard Tomàs
 
ASP.NET MVC Core
Eduard Tomàs
 
Azure functions
Eduard Tomàs
 
Asp.Net Core 1.0 Deep Dive
Eduard Tomàs
 

Recently uploaded (20)

PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
What companies do with Pharo (ESUG 2025)
ESUG
 
PDF
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PDF
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
PDF
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
PDF
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
PDF
Odoo Customization Services by CandidRoot Solutions
CandidRoot Solutions Private Limited
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
PDF
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
Operations Profile SPDX_Update_20250711_Example_05_03.pptx
Shane Coughlan
 
PPTX
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PPTX
Online Contractor Induction and Safety Induction Training Software
SHEQ Network Limited
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PPTX
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
What companies do with Pharo (ESUG 2025)
ESUG
 
Virtual Threads in Java: A New Dimension of Scalability and Performance
Tier1 app
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
Supabase Meetup: Build in a weekend, scale to millions
Carlo Gilmar Padilla Santana
 
How to Download and Install ADT (ABAP Development Tools) for Eclipse IDE | SA...
SAP Vista, an A L T Z E N Company
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Why Are More Businesses Choosing Partners Over Freelancers for Salesforce.pdf
Cymetrix Software
 
ChatPharo: an Open Architecture for Understanding How to Talk Live to LLMs
ESUG
 
Odoo Customization Services by CandidRoot Solutions
CandidRoot Solutions Private Limited
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
Infrastructure planning and resilience - Keith Hastings.pptx.pdf
Safe Software
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Operations Profile SPDX_Update_20250711_Example_05_03.pptx
Shane Coughlan
 
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Online Contractor Induction and Safety Induction Training Software
SHEQ Network Limited
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 

EcmaScript unchained

  • 5. Please don’t talk while the show is going on. Just sit down, eat popcorns and do not interrupt. Thanks.
  • 6. Interrupt me. Ask any question you have (no answered guaranteed :P) Let’s enjoy together!
  • 7. EcmaScript 2015 top new features
  • 9. function foo() { console.log(varidx); // Prints undefined as varidx is hoisted for (var varidx = 0; varidx < 10; varidx++) {; } console.log(varidx); // Prints 10 varidx = 100; } function foolet() { console.log(letidx); // Reference error for (let letidx = 0; letidx < 10; letidx++) {; } console.log(letidx); // Reference error letidx = 100; } function fooconst() { console.log(max); // Error (access to const before is initialized) const max = 10; max = 0; // Syntax error! }
  • 11. var Brewery = function(name) { this.name = name; this.beers = [ {name: "Punk IPA", style:"ipa"}, {name: "5 am", style: "pale ale"}, {name: "Tokio", style: "stout"}]; this.beersByType = function(type) { return this.beers.filter(function (element) { return element.style == type; }); } this.getBeersWithFullName = function() { return this.beers.map(function(element) { return { name: element.name + " by " + this.name, style: element.style}; }); } } Classic (ES5) code. Very verbose syntax
  • 12. The new arrow syntax var Brewery = function(name) { this.name = name; this.beers = [ {name: "Punk IPA", style:"ipa"}, {name: "5 am", style: "pale ale"}, {name: "Tokio", style: "stout"}]; this.beersByType = function(type) { return this.beers.filter(e => e.syle == type); } this.getBeersWithFullName = function() { return this.beers.map(function(element) { return { name: element.name + " by " + this.name, style: element.style}; }); } } this problem. What is the value of this inside the inner function?
  • 13. this.getBeersWithFullName = function () { var self = this; return this.beers.map(function (element) { return { name: element.name + " by " + self.name, style: element.style}; }); } Need to remember use the “self” variable instead of “this” in the inner function. Unnatural way to do things.
  • 14. this.getBeersWithFullName = function () { return this.beers.map(function (element) { return { name: element.name + " by " + this.name, style: element.style }; }.bind(this)); } Just need to call bind in the inner function to tie it to the previous this context. More elegant than using self, but still unnatural...
  • 15. Arrow functions do what ES should be done from the beginning: preserve the “this” context. this.getBeersWithFullName = function () { return this.beers.map(e => ({ name: e.name + " by " + this.name, style: e.style })); }
  • 16. Arrow functions do what ES should be done from the beginning: preserve the “this” context. this.getBeersWithFullName = function () { return this.beers.map(e => ({ name: e.name + " by " + this.name, style: e.style })); } Bonus: Do you notice the parens? ES parser needs them if arrow function returns a object in notation-object form.
  • 18. ES5 Standard code, using string concatenation to create the name property this.getBeersWithFullName = function () { return this.beers.map(e => ({ name: e.name + " by " + this.name, style: e.style })); }
  • 19. ES2015 code with string interpolation this.getBeersWithFullName = function () { return this.beers.map(e => ({ name: `${e.name} by ${this.name}`, style: e.style })); } Yes... We had two markers for strings in ES (single quotes and double quotes) but for string interoplation we will use a new third marker. Bonus: String interpolation works on multi-line strings. You can still use n if prefer, of course.
  • 21. var question = 'The answer to life the universe and everything'; var answer = 42; var base = { question, answer, toString: (() => `${this.question} is ${this.answer}`) }; var der = { __proto__: base, ['answer_' + (() => this.answer)()]: this.answer }
  • 23. We can use strings for object properties as usual We can create a Symbol using Symbol.for(“name”) or Symbol(“name”) And we can use this newly Symbol to create a new property for the object var obj = {}; obj[Symbol("a")] = "a"; obj[Symbol.for("b")] = "b"; obj["c"] = "c"; obj.d = "d"; for (var i in obj) { console.log(i); // logs "c" and "d" } But are not private! Welcome to Object.getOwnPropertySymbols() Properties stored in símbols don’t appear in for..in iterations nor in Object.getOwnPropertyNames()
  • 24. Of course... No string coertion exists on Symbols Symbol("a") == Symbol("a") // false Symbol("a") === Symbol("a") // false Symbol("a") == Symbol("a") // true Symbol.for("a") === Symbol.for("a") // true Symbol("a") == "a" // false Symbol.for("a") == "a" // false
  • 28. var values = [42, 69]; var x = 42; var y = 69; ES5 classic way of doing this var values = [42, 69]; var [x,y] = values; Same with ES2015 destructuring
  • 29. var x = 42; var y = 69; We want x = 69 and y = 42, but with one simple line of code... var x = 42; var y = 69; [x, y] = [y, x];
  • 30. This declares three variables, called c, d and e. Value of c is first variable of arr (4) Value of d is second variable of arr (8) Value of e is the rest values of arr (an array with 15, 16, 23 and 42) var arr = [4, 8, 15, 16, 23, 42]; var [c,d,...e ] = arr
  • 31. function foo(name, options, ...other) { // Some code } Inside foo: name is value of 1st parameter (or undefined) options is value of 2nd parameter (or undefined) other is an array with all the others paràmetres (or empty array but never undefined)
  • 32. Just keep in mind that x.f(...a) is equivalent to f.apply(x, a);
  • 34. An iterator is a function with a specific name [Symbol.iterator]. This function mush return an object with one method next(). The method next() must return an object with two properties: value: corrent value of iteration done: boolean that equals true if the last element has been reached. let fibonacci = { [Symbol.iterator]() { let pre = 0, cur = 1; return { next() { [pre, cur] = [cur, pre + cur]; return { done: false, value: cur } } } } } for (var n of fibonacci) { // truncate the sequence at 1000 if (n > 1000) break; console.log(n); } Notice the new for..of to iterate over all the values of the iterator of an object
  • 36. Use of function* to create the generator. Generators return iterators ([Symbol.iterator]) Use of yield to return “the next” value of the iterator If a generator never exits it returns a “never ending” iterator. Of course you must stop iterating it when no more vàlues are needed. var fibonacci = { [Symbol.iterator]: function*() { var pre = 0, cur = 1; for (;;) { var temp = pre; pre = cur; cur += temp; yield cur; } } } for (var n of fibonacci) { // truncate the sequence at 1000 if (n > 1000) break; console.log(n); }
  • 38. This is equivalent to the constructor function pattern in ES5 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return '(' + this.x + ', ' + this.y + ')'; } } Objects must be created with new and classes do not exist in runtime (typeof Point is ‘function’)
  • 40. class Point { constructor(x, y) { this.x = x; this.y = y; } // More stuff } class ColorPoint extends Point { constructor(x, y, color) { super(x, y); this.color = color; } // more stuff } let cp = new ColorPoint(25, 8, 'green');
  • 43. //------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } Any declaration prefixed by “export” keyword is an export of the module Using import keyword we can choose what of the exports of the module we want to include to the global namespace //------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5
  • 44. //------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } Any declaration prefixed by “export” keyword is an export of the module Using import keyword we can choose what of the exports of the module we want to include to the global namespace //------ main.js ------ import { square, diag } from 'lib'; console.log(square(11)); // 121 console.log(diag(4, 3)); // 5
  • 46. //------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } Any declaration prefixed by “export” keyword is an export of the module You can, of course, specify a namespace for the import, keeping the global namespace clean (at least all clean that the w3c guys allow us :P)... //------ main.js ------ import * as lib from 'lib'; console.log(lib.square(11)); // 121 console.log(lib.diag(4, 3)); // 5 Did you notice the use of * to import all the exports of a module?
  • 47. Module exports a class (note the use of default). Default exports must be named on import Module export just a function //------ MyClass.js ------ export default class { ... }; //------ main2.js ------ import MyClass from 'MyClass'; let inst = new MyClass(); //------ myFunc.js ------ export default function () { ... }; //------ main1.js ------ import myFunc from 'myFunc'; myFunc();
  • 48. This is not allowed in ES6 Less flexibility but no need to execute the code to find the imports or exports of a module. Can be optimized. var mylib; if (Math.random()) { mylib = require('foo'); } else { mylib = require('bar'); }
  • 49. Eduard Tomàs i Avellana #GAPAND2015