SlideShare une entreprise Scribd logo
1  sur  35
NEW IN ES2016
JAVASCRIPT'S FIRST YEARLY RELEASE
Brian Terlson
@bterlson
brian.terlson@microsoft.com
InfoQ.com: News & Community Site
• 750,000 unique visitors/month
• Published in 4 languages (English, Chinese, Japanese and Brazilian
Portuguese)
• Post content from our QCon conferences
• News 15-20 / week
• Articles 3-4 / week
• Presentations (videos) 12-15 / week
• Interviews 2-3 / week
• Books 1 / month
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations
/ecmascript-2016
Presented at QCon New York
www.qconnewyork.com
Purpose of QCon
- to empower software development by facilitating the spread of
knowledge and innovation
Strategy
- practitioner-driven conference designed for YOU: influencers of
change and innovation in your teams
- speakers and topics driving the evolution and innovation
- connecting and catalyzing the influencers and innovators
Highlights
- attended by more than 12,000 delegates since 2007
- held in 9 cities worldwide
AGENDA
• History
• Async Functions
• Observableas
• SIMD
• Decorators
• Value Types
ES2016 – BRING ON THE TRAIN MODEL
• Train leaves every year
• Mature proposals get on the train
• Multiple interoperable
implementations required
• test262 collateral required
• Work on Github:
https://github.com/tc39/ecma262 Image by speedemon08 CC BY NC SA 2.0
QUICK JAVASCRIPT FIX
String#at
"🚀".length  2
"🚀"[0]  "�"
"🚀".at(0)  "🚀"
HOW DO WE…
• Return a single value synchronously?
• Functions!
• Return many values synchronously?
• Generator Functions!
• Return a single value asynchronously?
• Promise-returning function?
• Async Functions!
async function fetch(url) {
return { ... }
}
fetch('/tc39.json')
.then(parseJSON)
.then(f => {
console.log(f.members.length);
});
async function fetch(url) {
let data = await $.get(url);
return JSON.parse(data);
}
fetch('/tc39.json')
.then(f => {
console.log(f.members.length);
});
async function fetch(url) {
try {
let data = await $.get(url);
return JSON.parse(data);
} catch (e) {
handleError(e);
}
}
fetch('/tc39.json')
.then(f => {
console.log(f.members.length);
});
ASYNC FUNCTIONS
https://github.com/tc39/ecmascript-asyncawait
Built on Promises and
Generators
Callable like any function
but:
• Returns a Promise
• `await` inside its
body
Similar to async/await in
C# and Dart
Implementations:
Babel, Traceur,
Regenerator
class Image {
async getData() { ... }
}
let obj = {
async fetch() { ... }
}
async (a, b) => await a + await b;
HOW DO WE…
• Return a single value synchronously?
• Functions!
• Return many values synchronously?
• Generator Functions
• Return a single value asynchronously?
• Async Functions
• Return many values asynchronously?
• Observables!
// Observer
let observer = {
next(value) {/* got value */},
throw(error) {
/* error getting values */ },
return() {/* no more values */}
};
// Observable
let observable = {
subscribe(observer) { ... }
}
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
// Observer
let observer = {
next(value) {/* got value */},
throw(error) { },
return() {/* no more values */}
};
// Observable
let d = new Observable(
obs => { obs.next(1); obs.return();}
);
d.subscribe(observer);
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
// Observer
let observer = function*() {
while(1) log("Got " + (yield));
}
// Observable
let d = new Observable(obs =>
{ obs.next(1); obs.return(); });
d.subscribe(observer());
// => "Got 1"
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
// Observer
let observer = prime(function*(){
while(1) log("Got " + (yield));
})
// Observable
let d = new Observable(obs =>
{ obs.next(1); obs.return(); });
d.subscribe(observer());
// => "Got 1"
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
let d = new Observable(obs =>{
obs.next(1); obs.next(2);
obs.return();
});
let d2 = d.map(n => n * 2);
d2.subscribe({
next: log
});
// => 2
// 4
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
let d = new Observable(obs =>{
obs.next(1); obs.next(2);
obs.return();
});
let d2 = d.map(n => n * 2);
d2.forEach(log);
// => 2
// 4
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
let d = new Observable(obs =>{
obs.next(1); obs.next(2);
obs.return();
});
let d2 = d.map(n => n * 2);
for async (n of d2) {
log(n);
}
// => 2
// 4
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
import {arrowKeys} from
'EventFilters';
let elem = $('document');
let keys = elem.listen('keypress');
let arrows = keys.filter(arrowKeys);
arrowKeys.forEach(moveCharacter);
OBSERVABLES
https://github.com/zenparsing/es-observable
Represents push-based
(async) data sources
• DOM events!
Lazy – no data emitted
until a consumer wants it
Built on the ES6 Generator
interface
Compositional: Chain
map/filter/etc. operations
Amenable to new syntax
QUICK JAVASCRIPT FIX
Exponentiation Operator:
Math.pow(10, 2)  10 ** 2
SIMD – SINGLE INSTRUCTION, MULTIPLE DATA
https://github.com/johnmccutchan/ecmascript_simd
• Hardware instructions for number crunching
• Exploits data parallelism to perform multiple
calculations simultaneously
• Benefits applications in fields like games, 3D
graphics, audio/video processing, multimedia
applications etc.
SIMD – SINGLE INSTRUCTION, MULTIPLE DATA
https://github.com/johnmccutchan/ecmascript_simd
Ax
Bx
Cx
Dx
Ay
By
Cy
Dy
Az
Bz
Cz
Dz
Scalar Operation
Ax
Bx
Cx
Dx
Ay
By
Cy
Dy
Az
Bz
Cz
Dz
SIMD Operation of vector length 4
let a = [0, 1, 2, 3];
let b = [4, 5, 6, 7];
let c = [a[0] + b[0],a[1] + b[1],a[2] + b[2],a[3] + b[3]]
let a = SIMD.int32x4(0, 1, 2, 3);
let b = SIMD.int32x4(4, 5, 6, 7);
let c = SIMD.int32x4.add(a, b);
SIMD – SINGLE INSTRUCTION, MULTIPLE DATA
https://github.com/johnmccutchan/ecmascript_simd
// normal sum
function sum(list) {
let sum = 0;
let len = list.length;
for (i = 0; i < len; i++){
sum += list[i];
}
return sum;
}
// SIMD sum
function sum(i32list) {
let sum = SIMD.int32x4.zero();
let len = i32list.length;
for (i = 0; i < len / 4; i++){
sum = SIMD.int32x4.add(
sum,
SIMD.Int32x4.load(
i32list,
i * 4
)
);
}
return sum[0] + sum[1] +
sum[2] + sum[3];
}
SIMD – SINGLE INSTRUCTION, MULTIPLE DATA
https://github.com/johnmccutchan/ecmascript_simd
DEMO
QUICK JAVASCRIPT FIX
String#rpad & String#lpad
"a".lpad(4)  " a";
class Person {
@memoize
get name() {
return this.first + this.last;
}
}
function memoize(target, name, desc) {
desc.set =
v => setValue(target, name, v);
desc.get =
() => getFromCache(target, name)||
originalGet(target);
}
DECORATORS
https://github.com/wycats/javascript-decorators
Modify behavior of things at
design time
Decoration of:
• Classes
• Properties
• Functions
• Parameters
In the future, decoration of
data properties
Decorators are just functions!
Early Implementation in
TypeScript 1.5
@Model
class Article {
@belongsTo author;
@hasMany comments;
constructor() { /* ... */ }
clear() { this.comments.deleteAll()}
}
@Model
class Author {
@hasMany articles;
constructor() { /* ... */ };
}
@Model
class Comment { /* ... */ }
// Example using factory
let f32x4 = Float32x4(0, 1, 2, 3);
let int8 = Int8(254);
// Example using literal suffixes
let i64 = 0L; // Int64
let ui64 = 0UL;// Uint64
let f32 = 0f; // Float32
let bignum = 0n; // Bignum
let dec = 0m; // Decimal
VALUE TYPES
https://github.com/brendaneich/value-spec (work in progress)
New Primitive Types:
• Int64/Uint64
• Bignum
• Decimal
• Complex
• Rational
• SIMD types
• TypedArray types
Literal Suffixes!
Benefits:
• Serialize across iframes
• Immutable
• === compares by value
// Measures.js
export let Yard =
ValueType(Symbol("Yard"), Float64);
export let Foot =
ValueType(Symbol("Feet"), Float64);
// Define literal suffixes (WIP!)
LiteralSuffixTable.ya = Yard;
LiteralSuffixTable.ft = Feet;
VALUE TYPES
https://github.com/brendaneich/value-spec (work in progress)
Custom Primitive Types!
Compose new primitive
types from existing ones
using the ValueType factory
Assign custom suffixes
Overload operators
// Measures.js
function addYandF(y, f) {
return Foot(y * 3 + f)
}
function addFandY(f, y) {
return addCandF(y, f)
}
Reflect.defineOperator('+', addYandF,
Yard, Foot);
Reflect.defineOperator('+', addFandY,
Foot, Yard);
VALUE TYPES
https://github.com/brendaneich/value-spec (work in progress)
Custom Primitive Types!
Compose new primitive
types from existing ones
using the ValueType factory
Assign custom suffixes
Overload operators
Import {Yard, Feet} from "Measures.js"
let pos = 87ya;
let pass = 20ft;
let newPos = pos + pass; // Foot(281)
// css math?
20em + 10px;
// vector math?
let v1 = Vector(1, 2);
let v2 = Vector(3, 4);
v1 + v2; // Vector(4, 6)
VALUE TYPES
https://github.com/brendaneich/value-spec (work in progress)
Custom Primitive Types!
Compose new primitive
types from existing ones
using the ValueType factory
Assign custom suffixes
Overload operators
Thank You!
Twitter: @bterlson
Github: https://github.com/bterlson
EASY WINS
Exponentiation Operator:
Math.pow(10, 2)  10 ** 2
String#rpad & String#lpad
"a".lpad(4)  " a";
String#at
"🚀"[0]  "�"
"🚀".at(0)  "🚀"
• async function* readLines(path) {
• let file = await fileOpen(path);
• try {
• while (!file.EOF)
• yield file.readLine();
• } finally {
• await file.close();
• }
• }
ASYNC GENERATORS
https://github.com/zenparsing/async-iteration/
• Builds on Promises, Generators,
and Async Functions
• `await` and `yield`
• `await` behaves like Async
Functions
• `yield` behaves like Generator
Functions
• Returns an Iterator-like object
• Has .next, .throw, and .return
• But each returns
Promise<IterationResult> rather
than IterationResult
• Includes new Async for-of loop
• let iter = readLines('/foo.txt');
• function read() {
• let p = iter.next();
• p.then(result => {
• if(result.done) return;
• print(result.value);
• read();
• });
• }
• read();
ASYNC GENERATORS
https://github.com/zenparsing/async-iteration/
• Builds on Promises, Generators,
and Async Functions
• `await` and `yield`
• `await` behaves like Async
Functions
• `yield` behaves like Generator
Functions
• Returns an Iterator-like object
• Has .next, .throw, and .return
• But each returns
Promise<IterationResult> rather
than IterationResult
• Includes new Async for-of loop
• for async (let line of
• readLines('foo.txt')
• ) {
• print(line);
• }
ASYNC GENERATORS
https://github.com/zenparsing/async-iteration/
• Builds on Promises, Generators,
and Async Functions
• `await` and `yield`
• `await` behaves like Async
Functions
• `yield` behaves like Generator
Functions
• Returns an Iterator-like object
• Has .next, .throw, and .return
• But each returns
Promise<IterationResult> rather
than IterationResult
• Includes new Async for-of loop
Watch the video with slide
synchronization on InfoQ.com!
http://www.infoq.com/presentations/
ecmascript-2016

Contenu connexe

Plus de C4Media

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoC4Media
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileC4Media
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020C4Media
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsC4Media
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No KeeperC4Media
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like OwnersC4Media
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaC4Media
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideC4Media
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDC4Media
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine LearningC4Media
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at SpeedC4Media
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsC4Media
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsC4Media
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerC4Media
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleC4Media
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeC4Media
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereC4Media
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing ForC4Media
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data EngineeringC4Media
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreC4Media
 

Plus de C4Media (20)

Streaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live VideoStreaming a Million Likes/Second: Real-Time Interactions on Live Video
Streaming a Million Likes/Second: Real-Time Interactions on Live Video
 
Next Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy MobileNext Generation Client APIs in Envoy Mobile
Next Generation Client APIs in Envoy Mobile
 
Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020Software Teams and Teamwork Trends Report Q1 2020
Software Teams and Teamwork Trends Report Q1 2020
 
Understand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java ApplicationsUnderstand the Trade-offs Using Compilers for Java Applications
Understand the Trade-offs Using Compilers for Java Applications
 
Kafka Needs No Keeper
Kafka Needs No KeeperKafka Needs No Keeper
Kafka Needs No Keeper
 
High Performing Teams Act Like Owners
High Performing Teams Act Like OwnersHigh Performing Teams Act Like Owners
High Performing Teams Act Like Owners
 
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to JavaDoes Java Need Inline Types? What Project Valhalla Can Bring to Java
Does Java Need Inline Types? What Project Valhalla Can Bring to Java
 
Service Meshes- The Ultimate Guide
Service Meshes- The Ultimate GuideService Meshes- The Ultimate Guide
Service Meshes- The Ultimate Guide
 
Shifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CDShifting Left with Cloud Native CI/CD
Shifting Left with Cloud Native CI/CD
 
CI/CD for Machine Learning
CI/CD for Machine LearningCI/CD for Machine Learning
CI/CD for Machine Learning
 
Fault Tolerance at Speed
Fault Tolerance at SpeedFault Tolerance at Speed
Fault Tolerance at Speed
 
Architectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep SystemsArchitectures That Scale Deep - Regaining Control in Deep Systems
Architectures That Scale Deep - Regaining Control in Deep Systems
 
ML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.jsML in the Browser: Interactive Experiences with Tensorflow.js
ML in the Browser: Interactive Experiences with Tensorflow.js
 
Build Your Own WebAssembly Compiler
Build Your Own WebAssembly CompilerBuild Your Own WebAssembly Compiler
Build Your Own WebAssembly Compiler
 
User & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix ScaleUser & Device Identity for Microservices @ Netflix Scale
User & Device Identity for Microservices @ Netflix Scale
 
Scaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's EdgeScaling Patterns for Netflix's Edge
Scaling Patterns for Netflix's Edge
 
Make Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home EverywhereMake Your Electron App Feel at Home Everywhere
Make Your Electron App Feel at Home Everywhere
 
The Talk You've Been Await-ing For
The Talk You've Been Await-ing ForThe Talk You've Been Await-ing For
The Talk You've Been Await-ing For
 
Future of Data Engineering
Future of Data EngineeringFuture of Data Engineering
Future of Data Engineering
 
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and MoreAutomated Testing for Terraform, Docker, Packer, Kubernetes, and More
Automated Testing for Terraform, Docker, Packer, Kubernetes, and More
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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 Scriptwesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
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)wesley chun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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...apidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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...Drew Madelung
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
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)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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...
 

New in ECMAScript 2016, JavaScript's First Yearly Release

  • 1. NEW IN ES2016 JAVASCRIPT'S FIRST YEARLY RELEASE Brian Terlson @bterlson brian.terlson@microsoft.com
  • 2. InfoQ.com: News & Community Site • 750,000 unique visitors/month • Published in 4 languages (English, Chinese, Japanese and Brazilian Portuguese) • Post content from our QCon conferences • News 15-20 / week • Articles 3-4 / week • Presentations (videos) 12-15 / week • Interviews 2-3 / week • Books 1 / month Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations /ecmascript-2016
  • 3. Presented at QCon New York www.qconnewyork.com Purpose of QCon - to empower software development by facilitating the spread of knowledge and innovation Strategy - practitioner-driven conference designed for YOU: influencers of change and innovation in your teams - speakers and topics driving the evolution and innovation - connecting and catalyzing the influencers and innovators Highlights - attended by more than 12,000 delegates since 2007 - held in 9 cities worldwide
  • 4. AGENDA • History • Async Functions • Observableas • SIMD • Decorators • Value Types
  • 5.
  • 6. ES2016 – BRING ON THE TRAIN MODEL • Train leaves every year • Mature proposals get on the train • Multiple interoperable implementations required • test262 collateral required • Work on Github: https://github.com/tc39/ecma262 Image by speedemon08 CC BY NC SA 2.0
  • 7. QUICK JAVASCRIPT FIX String#at "🚀".length  2 "🚀"[0]  "�" "🚀".at(0)  "🚀"
  • 8. HOW DO WE… • Return a single value synchronously? • Functions! • Return many values synchronously? • Generator Functions! • Return a single value asynchronously? • Promise-returning function? • Async Functions!
  • 9. async function fetch(url) { return { ... } } fetch('/tc39.json') .then(parseJSON) .then(f => { console.log(f.members.length); }); async function fetch(url) { let data = await $.get(url); return JSON.parse(data); } fetch('/tc39.json') .then(f => { console.log(f.members.length); }); async function fetch(url) { try { let data = await $.get(url); return JSON.parse(data); } catch (e) { handleError(e); } } fetch('/tc39.json') .then(f => { console.log(f.members.length); }); ASYNC FUNCTIONS https://github.com/tc39/ecmascript-asyncawait Built on Promises and Generators Callable like any function but: • Returns a Promise • `await` inside its body Similar to async/await in C# and Dart Implementations: Babel, Traceur, Regenerator class Image { async getData() { ... } } let obj = { async fetch() { ... } } async (a, b) => await a + await b;
  • 10. HOW DO WE… • Return a single value synchronously? • Functions! • Return many values synchronously? • Generator Functions • Return a single value asynchronously? • Async Functions • Return many values asynchronously? • Observables!
  • 11. // Observer let observer = { next(value) {/* got value */}, throw(error) { /* error getting values */ }, return() {/* no more values */} }; // Observable let observable = { subscribe(observer) { ... } } OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 12. // Observer let observer = { next(value) {/* got value */}, throw(error) { }, return() {/* no more values */} }; // Observable let d = new Observable( obs => { obs.next(1); obs.return();} ); d.subscribe(observer); OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 13. // Observer let observer = function*() { while(1) log("Got " + (yield)); } // Observable let d = new Observable(obs => { obs.next(1); obs.return(); }); d.subscribe(observer()); // => "Got 1" OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 14. // Observer let observer = prime(function*(){ while(1) log("Got " + (yield)); }) // Observable let d = new Observable(obs => { obs.next(1); obs.return(); }); d.subscribe(observer()); // => "Got 1" OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 15. let d = new Observable(obs =>{ obs.next(1); obs.next(2); obs.return(); }); let d2 = d.map(n => n * 2); d2.subscribe({ next: log }); // => 2 // 4 OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 16. let d = new Observable(obs =>{ obs.next(1); obs.next(2); obs.return(); }); let d2 = d.map(n => n * 2); d2.forEach(log); // => 2 // 4 OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 17. let d = new Observable(obs =>{ obs.next(1); obs.next(2); obs.return(); }); let d2 = d.map(n => n * 2); for async (n of d2) { log(n); } // => 2 // 4 OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 18. import {arrowKeys} from 'EventFilters'; let elem = $('document'); let keys = elem.listen('keypress'); let arrows = keys.filter(arrowKeys); arrowKeys.forEach(moveCharacter); OBSERVABLES https://github.com/zenparsing/es-observable Represents push-based (async) data sources • DOM events! Lazy – no data emitted until a consumer wants it Built on the ES6 Generator interface Compositional: Chain map/filter/etc. operations Amenable to new syntax
  • 19. QUICK JAVASCRIPT FIX Exponentiation Operator: Math.pow(10, 2)  10 ** 2
  • 20. SIMD – SINGLE INSTRUCTION, MULTIPLE DATA https://github.com/johnmccutchan/ecmascript_simd • Hardware instructions for number crunching • Exploits data parallelism to perform multiple calculations simultaneously • Benefits applications in fields like games, 3D graphics, audio/video processing, multimedia applications etc.
  • 21. SIMD – SINGLE INSTRUCTION, MULTIPLE DATA https://github.com/johnmccutchan/ecmascript_simd Ax Bx Cx Dx Ay By Cy Dy Az Bz Cz Dz Scalar Operation Ax Bx Cx Dx Ay By Cy Dy Az Bz Cz Dz SIMD Operation of vector length 4 let a = [0, 1, 2, 3]; let b = [4, 5, 6, 7]; let c = [a[0] + b[0],a[1] + b[1],a[2] + b[2],a[3] + b[3]] let a = SIMD.int32x4(0, 1, 2, 3); let b = SIMD.int32x4(4, 5, 6, 7); let c = SIMD.int32x4.add(a, b);
  • 22. SIMD – SINGLE INSTRUCTION, MULTIPLE DATA https://github.com/johnmccutchan/ecmascript_simd // normal sum function sum(list) { let sum = 0; let len = list.length; for (i = 0; i < len; i++){ sum += list[i]; } return sum; } // SIMD sum function sum(i32list) { let sum = SIMD.int32x4.zero(); let len = i32list.length; for (i = 0; i < len / 4; i++){ sum = SIMD.int32x4.add( sum, SIMD.Int32x4.load( i32list, i * 4 ) ); } return sum[0] + sum[1] + sum[2] + sum[3]; }
  • 23. SIMD – SINGLE INSTRUCTION, MULTIPLE DATA https://github.com/johnmccutchan/ecmascript_simd DEMO
  • 24. QUICK JAVASCRIPT FIX String#rpad & String#lpad "a".lpad(4)  " a";
  • 25. class Person { @memoize get name() { return this.first + this.last; } } function memoize(target, name, desc) { desc.set = v => setValue(target, name, v); desc.get = () => getFromCache(target, name)|| originalGet(target); } DECORATORS https://github.com/wycats/javascript-decorators Modify behavior of things at design time Decoration of: • Classes • Properties • Functions • Parameters In the future, decoration of data properties Decorators are just functions! Early Implementation in TypeScript 1.5 @Model class Article { @belongsTo author; @hasMany comments; constructor() { /* ... */ } clear() { this.comments.deleteAll()} } @Model class Author { @hasMany articles; constructor() { /* ... */ }; } @Model class Comment { /* ... */ }
  • 26. // Example using factory let f32x4 = Float32x4(0, 1, 2, 3); let int8 = Int8(254); // Example using literal suffixes let i64 = 0L; // Int64 let ui64 = 0UL;// Uint64 let f32 = 0f; // Float32 let bignum = 0n; // Bignum let dec = 0m; // Decimal VALUE TYPES https://github.com/brendaneich/value-spec (work in progress) New Primitive Types: • Int64/Uint64 • Bignum • Decimal • Complex • Rational • SIMD types • TypedArray types Literal Suffixes! Benefits: • Serialize across iframes • Immutable • === compares by value
  • 27. // Measures.js export let Yard = ValueType(Symbol("Yard"), Float64); export let Foot = ValueType(Symbol("Feet"), Float64); // Define literal suffixes (WIP!) LiteralSuffixTable.ya = Yard; LiteralSuffixTable.ft = Feet; VALUE TYPES https://github.com/brendaneich/value-spec (work in progress) Custom Primitive Types! Compose new primitive types from existing ones using the ValueType factory Assign custom suffixes Overload operators
  • 28. // Measures.js function addYandF(y, f) { return Foot(y * 3 + f) } function addFandY(f, y) { return addCandF(y, f) } Reflect.defineOperator('+', addYandF, Yard, Foot); Reflect.defineOperator('+', addFandY, Foot, Yard); VALUE TYPES https://github.com/brendaneich/value-spec (work in progress) Custom Primitive Types! Compose new primitive types from existing ones using the ValueType factory Assign custom suffixes Overload operators
  • 29. Import {Yard, Feet} from "Measures.js" let pos = 87ya; let pass = 20ft; let newPos = pos + pass; // Foot(281) // css math? 20em + 10px; // vector math? let v1 = Vector(1, 2); let v2 = Vector(3, 4); v1 + v2; // Vector(4, 6) VALUE TYPES https://github.com/brendaneich/value-spec (work in progress) Custom Primitive Types! Compose new primitive types from existing ones using the ValueType factory Assign custom suffixes Overload operators
  • 30. Thank You! Twitter: @bterlson Github: https://github.com/bterlson
  • 31. EASY WINS Exponentiation Operator: Math.pow(10, 2)  10 ** 2 String#rpad & String#lpad "a".lpad(4)  " a"; String#at "🚀"[0]  "�" "🚀".at(0)  "🚀"
  • 32. • async function* readLines(path) { • let file = await fileOpen(path); • try { • while (!file.EOF) • yield file.readLine(); • } finally { • await file.close(); • } • } ASYNC GENERATORS https://github.com/zenparsing/async-iteration/ • Builds on Promises, Generators, and Async Functions • `await` and `yield` • `await` behaves like Async Functions • `yield` behaves like Generator Functions • Returns an Iterator-like object • Has .next, .throw, and .return • But each returns Promise<IterationResult> rather than IterationResult • Includes new Async for-of loop
  • 33. • let iter = readLines('/foo.txt'); • function read() { • let p = iter.next(); • p.then(result => { • if(result.done) return; • print(result.value); • read(); • }); • } • read(); ASYNC GENERATORS https://github.com/zenparsing/async-iteration/ • Builds on Promises, Generators, and Async Functions • `await` and `yield` • `await` behaves like Async Functions • `yield` behaves like Generator Functions • Returns an Iterator-like object • Has .next, .throw, and .return • But each returns Promise<IterationResult> rather than IterationResult • Includes new Async for-of loop
  • 34. • for async (let line of • readLines('foo.txt') • ) { • print(line); • } ASYNC GENERATORS https://github.com/zenparsing/async-iteration/ • Builds on Promises, Generators, and Async Functions • `await` and `yield` • `await` behaves like Async Functions • `yield` behaves like Generator Functions • Returns an Iterator-like object • Has .next, .throw, and .return • But each returns Promise<IterationResult> rather than IterationResult • Includes new Async for-of loop
  • 35. Watch the video with slide synchronization on InfoQ.com! http://www.infoq.com/presentations/ ecmascript-2016