SlideShare a Scribd company logo
EcmaScript 2015impress your friends at the party
What is es6?
Why es6?
Is it Safe to Us Es6?!?!
https://kangax.github.io/compat-table/es6/
How do we use Es6?
https://github.com/rauschma/webpack-es6-demo
https://github.com/angular-class/NG6-starter
Syntactic SugAr
Es6 Classes
ES6 Classes
• Simple sugar over the the prototype-based
OO pattern

• A more convenient form makes classes
easier to use 

• Classes support inheritance, super calls,
instance and static methods and
constructors
class Project {

constructor(name) {

this.name = name;

}



start() {

return `Project ${this.name} starting`;

}

}



var project = new Project("Website");

project.start(); // "Project Website starting"
Es6 Inheritance
ES6 INheritance
• Inheritance is possible via the prototype

• You can inherit from a base class using the
extends keyword

• You must call super before you can access
this in a subclass
class Shape {

…

toString () {

return `Shape(${this.id})`

}

}

class Rectangle extends Shape {

constructor (id, x, y, width, height) {

super(id, x, y)

…

}

toString () {

return "Rectangle > " + super.toString()

}

}

class Circle extends Shape {

constructor (id, x, y, radius) {

super(id, x, y)

…

}

toString () {

return "Circle > " + super.toString()

}

}
Es6 Modules
ES6 MODULES
• Language-level support for modules for
component definition

• Best of both both CommonJS and AMD 

• Named exports and default exports
//------ 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));

}



//------ main.js ------

import { square, diag } from 'lib';

console.log(square(11)); // 121

console.log(diag(4, 3)); // 5
//------ main.js ------

import * as lib from 'lib';

console.log(lib.square(11)); // 121

console.log(lib.diag(4, 3)); // 5
//------ myFunc.js ------

export default function () { ... };



//------ main1.js ------

import myFunc from 'myFunc';

myFunc();
//------ MyClass.js ------

export default class { ... };



//------ main2.js ------

import MyClass from 'MyClass';

let inst = new MyClass();
Es6 Block Level Scoping
ES6 MODULES
• Function scope can be tricky!

• We can scope variables at a block level
using let and const
function printName() {

if(true) {

var name = "Rafael";

}

console.log(name); // Rafael

}
function printName() {

var name; // variable declaration is hoisted to the top

if(true) {

name = "Rafael";

}

console.log(name); // Rafael

}
function printName() {

if(true) {

let name = "Rafael";

}

console.log(name); // ReferenceError: name is not defined

}
function printName() {

var name = "Hey";

if(true) {

let name = "Rafael";

console.log(name); // Rafael

}

console.log(name); // Hey

}
if (true) { // enter new scope, TDZ starts



// Uninitialized binding for `tmp` is created

tmp = 'abc'; // ReferenceError

console.log(tmp); // ReferenceError



let tmp; // TDZ ends, `tmp` is initialized with `undefined`

console.log(tmp); // undefined



tmp = 123;

console.log(tmp); // 123

}
Es6 Arrow functions
ES6 Arrow Functions
• Arrow function expression aka fat arrow
functions are a shorter syntax

• Lexically binds the this value

• Arrow functions are always anonymous
var numbers = [1,2,3,4,5];

var timesTwo = numbers.map(function (number) {

return number * 2;

});

console.log(timesTwo); // [2, 4, 6, 8, 10]
var numbers = [1,2,3,4,5];

var timesTwo = numbers.map((number) => number * 2);

console.log(timesTwo); // [2, 4, 6, 8, 10]
var numbers = [1,2,3,4,5];

var timesTwo = numbers.map(number => number * 2);

console.log(timesTwo); // [2, 4, 6, 8, 10]
function FooCtrl (FooService) {

this.foo = 'Hello';

FooService

.doSomething(function (response) {

this.foo = response;

});

}
function FooCtrl (FooService) {

this.foo = 'Hello';

FooService

.doSomething(function (response) {

this.foo = response;

}.bind(this));

}
function FooCtrl (FooService) {

var that = this;

that.foo = 'Hello';

FooService

.doSomething(function (response) {

that.foo = response;

});

}
function FooCtrl (FooService) {

this.foo = 'Hello';

FooService

.doSomething((response) => { // woo, pretty

this.foo = response;

});

}
function FooCtrl (FooService) {

this.foo = 'Hello';

FooService

.doSomething(response => this.foo = response);

}
Es6 Template Strings
ES6 Template strings
• Multi-line strings

• Expression interpolation

• Do not let untrusted users construct
template strings!
console.log("string text line 1n"+

"string text line 2");

// "string text line 1

// string text line 2"
console.log(`string text line 1

string text line 2`);

// "string text line 1

// string text line 2"
var a = 5;

var b = 10;

console.log("Fifteen is " + (a + b) + " andnnot " +
(2 * a + b) + ".");

// "Fifteen is 15 and

// not 20."
var a = 5;

var b = 10;

console.log(`Fifteen is ${a + b} andnnot ${2 * a + b}.`);

// "Fifteen is 15 and

// not 20."
Es6 Object Literals
ES6 Object Literals
• Object literals are extended to be more
convenient and more like defining a class

• Better property and method declarations
var x = 10;

var y = 30;



var coordinates = {

x: x,

y: y

};



console.log(coordinates); // { x: 10, y: 30 }
let x = 10;

let y = 30;



let coordinates = { x, y };



console.log(coordinates); // { x: 10, y: 30 }
let x = 10;

let y = 30;



let coordinates = {

x,

y,

z: 10,

};



console.log(coordinates); // { x: 10, y: 30, z: 10 }
var cart = {

_items: [],

addItem: function(item) {

this._items.push(item);



return this;

},

toString: function() {

return this._items.join(', ');

}

}



cart.addItem('apple')

.addItem('orange')

.addItem('banana');



console.log(cart.toString()); // apple, orange, banana
var cart = {

_items: [],

addItem(item) {

this._items.push(item);



return this;

},

toString() {

return this._items.join(', ');

}

}



cart.addItem('apple')

.addItem('orange')

.addItem('banana');



console.log(cart.toString()); // apple, orange, banana
Es6 Array API
ES6 Array API
• Array.from converts array-like objects into arrays 

• Array.keys, Array.values and Array.entries are
handy for iterating over arrays

• Array.find returns the first element that the
callback returns true
•Array.findIndex returns the index of the first
element that the callback returns true
// Array-like object (arguments) to Array

function f() {

return Array.from(arguments);

}



f(1, 2, 3);

// [1, 2, 3]





// Any iterable object...

// Set

var s = new Set(["foo", window]);

Array.from(s);

// ["foo", window]





// Map

var m = new Map([[1, 2], [2, 4], [4, 8]]);

Array.from(m);

// [[1, 2], [2, 4], [4, 8]]





// String

Array.from("foo");

// ["f", "o", "o"]

var arr = ["a", "b", "c"];

var iterator = arr.keys();



console.log(iterator.next()); // { value: 0, done: false }

console.log(iterator.next()); // { value: 1, done: false }

console.log(iterator.next()); // { value: 2, done: false }

console.log(iterator.next()); // { value: undefined, done: true }
var arr = ['w', 'y', 'k', 'o', 'p'];

var eArr = arr.values();

console.log(eArr.next().value); // w

console.log(eArr.next().value); // y

console.log(eArr.next().value); // k

console.log(eArr.next().value); // o

console.log(eArr.next().value); // p
var arr = ['a', 'b', 'c'];

var eArr = arr.entries();



console.log(eArr.next().value); // [0, 'a']

console.log(eArr.next().value); // [1, 'b']

console.log(eArr.next().value); // [2, 'c']
function isPrime(element, index, array) {

var start = 2;

while (start <= Math.sqrt(element)) {

if (element % start++ < 1) {

return false;

}

}

return element > 1;

}



console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found

console.log([4, 5, 8, 12].find(isPrime)); // 5
function isPrime(element, index, array) {

var start = 2;

while (start <= Math.sqrt(element)) {

if (element % start++ < 1) {

return false;

}

}

return element > 1;

}



console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found

console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
Es6 SET
ES6 SET
• Lets you store unique values of any type

• You can store primitive values or object
references
var mySet = new Set();



mySet.add(1);

mySet.add(5);

mySet.add("some text");



mySet.has(1); // true

mySet.has(3); // false, 3 has not been added to the set

mySet.has(5); // true

mySet.has(Math.sqrt(25)); // true

mySet.has("Some Text".toLowerCase()); // true



mySet.size; // 3



mySet.delete(5); // removes 5 from the set

mySet.has(5); // false, 5 has been removed



mySet.size; // 2, we just removed one value
Es6 MAP
ES6 MAP
• Simple key/value map

• Any value (object or primitive value) can be
used as either a key or a value
var myMap = new Map();



var keyObj = {},

keyFunc = function () {},

keyString = "a string";



// setting the values

myMap.set(keyString, "value associated with 'a string'");

myMap.set(keyObj, "value associated with keyObj");

myMap.set(keyFunc, "value associated with keyFunc");



myMap.size; // 3



// getting the values

myMap.get(keyString); // "value associated with 'a string'"

myMap.get(keyObj); // "value associated with keyObj"

myMap.get(keyFunc); // "value associated with keyFunc"



myMap.get("a string"); // "value associated with 'a string'"

// because keyString === 'a string'

myMap.get({}); // undefined, because keyObj !== {}

myMap.get(function() {}) // undefined, because keyFunc !==
function () {}
Es6 Resources
https://leanpub.com/exploring-es6/
http://es6-features.org/
http://es6katas.org/
http://www.es6fiddle.net/
http://es6-features.org/
http://www.2ality.com/
https://github.com/lukehoban/es6features
http://codepen.io/bradleyboy/posts/getting-to-know-es6-object-literals
http://jamesknelson.com/es6-the-bits-youll-actually-use
http://jamesknelson.com/es6-cheatsheet.png
Thank you!

More Related Content

What's hot

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemyInada Naoki
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Nate Abele
 
Google Guava
Google GuavaGoogle Guava
Google Guava
Scott Leberknight
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodecamp Romania
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
Igor Anishchenko
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Fedor Lavrentyev
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
Nate Abele
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
Augusto Pascutti
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
Kris Wallsmith
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
mengukagan
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8PrinceGuru MS
 
Promise it's partial
Promise it's partialPromise it's partial
Promise it's partial
Jim Argeropoulos
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in Django
Remco Wendt
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
Baruch Sadogursky
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
Christine Cheung
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5
Corey Ballou
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
Jeff Carouth
 

What's hot (20)

PofEAA and SQLAlchemy
PofEAA and SQLAlchemyPofEAA and SQLAlchemy
PofEAA and SQLAlchemy
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
CodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical GroovyCodeCamp Iasi 10 march 2012 - Practical Groovy
CodeCamp Iasi 10 march 2012 - Practical Groovy
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev FedorProgramming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
An introduction to SQLAlchemy
An introduction to SQLAlchemyAn introduction to SQLAlchemy
An introduction to SQLAlchemy
 
Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8Corephpcomponentpresentation 1211425966721657-8
Corephpcomponentpresentation 1211425966721657-8
 
Promise it's partial
Promise it's partialPromise it's partial
Promise it's partial
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in Django
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 

Viewers also liked

Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
Rafael Glanzner
 
AngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTMLAngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTML
Lukas Ruebbelke
 
Turn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with AngularTurn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with Angular
Lukas Ruebbelke
 
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJSngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
Lukas Ruebbelke
 
ngAnimate crash course
ngAnimate crash coursengAnimate crash course
ngAnimate crash course
Lukas Ruebbelke
 
Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!
Lukas Ruebbelke
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Lukas Ruebbelke
 
The REAL Angular Keynote
The REAL Angular KeynoteThe REAL Angular Keynote
The REAL Angular Keynote
Lukas Ruebbelke
 
Embrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.xEmbrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.x
Lukas Ruebbelke
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
Viliam Elischer
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
Lukas Ruebbelke
 
Ionic Crash Course! Hack-a-ton SF
Ionic Crash Course! Hack-a-ton SFIonic Crash Course! Hack-a-ton SF
Ionic Crash Course! Hack-a-ton SF
Lukas Ruebbelke
 
Summer internship report | repairwale.com mobile application design and devel...
Summer internship report | repairwale.com mobile application design and devel...Summer internship report | repairwale.com mobile application design and devel...
Summer internship report | repairwale.com mobile application design and devel...
Rajath Thomson
 

Viewers also liked (13)

Introduction to angular 2
Introduction to angular 2Introduction to angular 2
Introduction to angular 2
 
AngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTMLAngularJS Directives - DSL for your HTML
AngularJS Directives - DSL for your HTML
 
Turn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with AngularTurn Your Designers Into Death Stars with Angular
Turn Your Designers Into Death Stars with Angular
 
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJSngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
ngEurope 2014: Become a Realtime Cage Dragon with Firebase and AngularJS
 
ngAnimate crash course
ngAnimate crash coursengAnimate crash course
ngAnimate crash course
 
Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!Badges? We don't need no stinkin' badges!
Badges? We don't need no stinkin' badges!
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
 
The REAL Angular Keynote
The REAL Angular KeynoteThe REAL Angular Keynote
The REAL Angular Keynote
 
Embrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.xEmbrace the Angular 2 Ethos in Angular 1.x
Embrace the Angular 2 Ethos in Angular 1.x
 
RxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScriptRxJS - The Reactive extensions for JavaScript
RxJS - The Reactive extensions for JavaScript
 
Get that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and ElectronGet that Corner Office with Angular 2 and Electron
Get that Corner Office with Angular 2 and Electron
 
Ionic Crash Course! Hack-a-ton SF
Ionic Crash Course! Hack-a-ton SFIonic Crash Course! Hack-a-ton SF
Ionic Crash Course! Hack-a-ton SF
 
Summer internship report | repairwale.com mobile application design and devel...
Summer internship report | repairwale.com mobile application design and devel...Summer internship report | repairwale.com mobile application design and devel...
Summer internship report | repairwale.com mobile application design and devel...
 

Similar to Impress Your Friends with EcmaScript 2015

Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
Jeff Strauss
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
Ximing Dai
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
Justin Alexander
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
The Software House
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
GephenSG
 
ScalaFlavor4J
ScalaFlavor4JScalaFlavor4J
ScalaFlavor4J
Kazuhiro Sera
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
David Atchley
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
johndaviddalton
 
ES6 Simplified
ES6 SimplifiedES6 Simplified
ES6 Simplified
Carlos Ble
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
Shakhzod Tojiyev
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
marcheiligers
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015qmmr
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
Santosh Wadghule
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
Mohd Saeed
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

Similar to Impress Your Friends with EcmaScript 2015 (20)

Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Adding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer ToolboxAdding ES6 to Your Developer Toolbox
Adding ES6 to Your Developer Toolbox
 
Exploring ES6
Exploring ES6Exploring ES6
Exploring ES6
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
"let ECMAScript = 6"
"let ECMAScript = 6" "let ECMAScript = 6"
"let ECMAScript = 6"
 
ECMAScript 6 new features
ECMAScript 6 new featuresECMAScript 6 new features
ECMAScript 6 new features
 
ScalaFlavor4J
ScalaFlavor4JScalaFlavor4J
ScalaFlavor4J
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
JSConf: All You Can Leet
JSConf: All You Can LeetJSConf: All You Can Leet
JSConf: All You Can Leet
 
ES6 Simplified
ES6 SimplifiedES6 Simplified
ES6 Simplified
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
JavaScript Classes and Inheritance
JavaScript Classes and InheritanceJavaScript Classes and Inheritance
JavaScript Classes and Inheritance
 
ECMAScript2015
ECMAScript2015ECMAScript2015
ECMAScript2015
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Getting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascriptGetting started with ES6 : Future of javascript
Getting started with ES6 : Future of javascript
 
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
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 

Recently uploaded

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 

Recently uploaded (20)

IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 

Impress Your Friends with EcmaScript 2015

  • 1. EcmaScript 2015impress your friends at the party
  • 4. Is it Safe to Us Es6?!?!
  • 6. How do we use Es6?
  • 7.
  • 8.
  • 12.
  • 14.
  • 15. ES6 Classes • Simple sugar over the the prototype-based OO pattern • A more convenient form makes classes easier to use • Classes support inheritance, super calls, instance and static methods and constructors
  • 16. class Project {
 constructor(name) {
 this.name = name;
 }
 
 start() {
 return `Project ${this.name} starting`;
 }
 }
 
 var project = new Project("Website");
 project.start(); // "Project Website starting"
  • 18. ES6 INheritance • Inheritance is possible via the prototype • You can inherit from a base class using the extends keyword • You must call super before you can access this in a subclass
  • 19. class Shape {
 …
 toString () {
 return `Shape(${this.id})`
 }
 }
 class Rectangle extends Shape {
 constructor (id, x, y, width, height) {
 super(id, x, y)
 …
 }
 toString () {
 return "Rectangle > " + super.toString()
 }
 }
 class Circle extends Shape {
 constructor (id, x, y, radius) {
 super(id, x, y)
 …
 }
 toString () {
 return "Circle > " + super.toString()
 }
 }
  • 21. ES6 MODULES • Language-level support for modules for component definition • Best of both both CommonJS and AMD • Named exports and default exports
  • 22. //------ 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));
 }
 
 //------ main.js ------
 import { square, diag } from 'lib';
 console.log(square(11)); // 121
 console.log(diag(4, 3)); // 5
  • 23. //------ main.js ------
 import * as lib from 'lib';
 console.log(lib.square(11)); // 121
 console.log(lib.diag(4, 3)); // 5
  • 24. //------ myFunc.js ------
 export default function () { ... };
 
 //------ main1.js ------
 import myFunc from 'myFunc';
 myFunc();
  • 25. //------ MyClass.js ------
 export default class { ... };
 
 //------ main2.js ------
 import MyClass from 'MyClass';
 let inst = new MyClass();
  • 26. Es6 Block Level Scoping
  • 27.
  • 28. ES6 MODULES • Function scope can be tricky! • We can scope variables at a block level using let and const
  • 29. function printName() {
 if(true) {
 var name = "Rafael";
 }
 console.log(name); // Rafael
 }
  • 30. function printName() {
 var name; // variable declaration is hoisted to the top
 if(true) {
 name = "Rafael";
 }
 console.log(name); // Rafael
 }
  • 31. function printName() {
 if(true) {
 let name = "Rafael";
 }
 console.log(name); // ReferenceError: name is not defined
 }
  • 32. function printName() {
 var name = "Hey";
 if(true) {
 let name = "Rafael";
 console.log(name); // Rafael
 }
 console.log(name); // Hey
 }
  • 33.
  • 34. if (true) { // enter new scope, TDZ starts
 
 // Uninitialized binding for `tmp` is created
 tmp = 'abc'; // ReferenceError
 console.log(tmp); // ReferenceError
 
 let tmp; // TDZ ends, `tmp` is initialized with `undefined`
 console.log(tmp); // undefined
 
 tmp = 123;
 console.log(tmp); // 123
 }
  • 36.
  • 37. ES6 Arrow Functions • Arrow function expression aka fat arrow functions are a shorter syntax • Lexically binds the this value • Arrow functions are always anonymous
  • 38. var numbers = [1,2,3,4,5];
 var timesTwo = numbers.map(function (number) {
 return number * 2;
 });
 console.log(timesTwo); // [2, 4, 6, 8, 10]
  • 39. var numbers = [1,2,3,4,5];
 var timesTwo = numbers.map((number) => number * 2);
 console.log(timesTwo); // [2, 4, 6, 8, 10]
  • 40. var numbers = [1,2,3,4,5];
 var timesTwo = numbers.map(number => number * 2);
 console.log(timesTwo); // [2, 4, 6, 8, 10]
  • 41. function FooCtrl (FooService) {
 this.foo = 'Hello';
 FooService
 .doSomething(function (response) {
 this.foo = response;
 });
 }
  • 42. function FooCtrl (FooService) {
 this.foo = 'Hello';
 FooService
 .doSomething(function (response) {
 this.foo = response;
 }.bind(this));
 }
  • 43. function FooCtrl (FooService) {
 var that = this;
 that.foo = 'Hello';
 FooService
 .doSomething(function (response) {
 that.foo = response;
 });
 }
  • 44. function FooCtrl (FooService) {
 this.foo = 'Hello';
 FooService
 .doSomething((response) => { // woo, pretty
 this.foo = response;
 });
 }
  • 45. function FooCtrl (FooService) {
 this.foo = 'Hello';
 FooService
 .doSomething(response => this.foo = response);
 }
  • 47. ES6 Template strings • Multi-line strings • Expression interpolation • Do not let untrusted users construct template strings!
  • 48. console.log("string text line 1n"+
 "string text line 2");
 // "string text line 1
 // string text line 2"
  • 49. console.log(`string text line 1
 string text line 2`);
 // "string text line 1
 // string text line 2"
  • 50. var a = 5;
 var b = 10;
 console.log("Fifteen is " + (a + b) + " andnnot " + (2 * a + b) + ".");
 // "Fifteen is 15 and
 // not 20."
  • 51. var a = 5;
 var b = 10;
 console.log(`Fifteen is ${a + b} andnnot ${2 * a + b}.`);
 // "Fifteen is 15 and
 // not 20."
  • 53. ES6 Object Literals • Object literals are extended to be more convenient and more like defining a class • Better property and method declarations
  • 54. var x = 10;
 var y = 30;
 
 var coordinates = {
 x: x,
 y: y
 };
 
 console.log(coordinates); // { x: 10, y: 30 }
  • 55. let x = 10;
 let y = 30;
 
 let coordinates = { x, y };
 
 console.log(coordinates); // { x: 10, y: 30 }
  • 56. let x = 10;
 let y = 30;
 
 let coordinates = {
 x,
 y,
 z: 10,
 };
 
 console.log(coordinates); // { x: 10, y: 30, z: 10 }
  • 57. var cart = {
 _items: [],
 addItem: function(item) {
 this._items.push(item);
 
 return this;
 },
 toString: function() {
 return this._items.join(', ');
 }
 }
 
 cart.addItem('apple')
 .addItem('orange')
 .addItem('banana');
 
 console.log(cart.toString()); // apple, orange, banana
  • 58. var cart = {
 _items: [],
 addItem(item) {
 this._items.push(item);
 
 return this;
 },
 toString() {
 return this._items.join(', ');
 }
 }
 
 cart.addItem('apple')
 .addItem('orange')
 .addItem('banana');
 
 console.log(cart.toString()); // apple, orange, banana
  • 60. ES6 Array API • Array.from converts array-like objects into arrays • Array.keys, Array.values and Array.entries are handy for iterating over arrays • Array.find returns the first element that the callback returns true •Array.findIndex returns the index of the first element that the callback returns true
  • 61. // Array-like object (arguments) to Array
 function f() {
 return Array.from(arguments);
 }
 
 f(1, 2, 3);
 // [1, 2, 3]
 
 
 // Any iterable object...
 // Set
 var s = new Set(["foo", window]);
 Array.from(s);
 // ["foo", window]
 
 
 // Map
 var m = new Map([[1, 2], [2, 4], [4, 8]]);
 Array.from(m);
 // [[1, 2], [2, 4], [4, 8]]
 
 
 // String
 Array.from("foo");
 // ["f", "o", "o"]

  • 62. var arr = ["a", "b", "c"];
 var iterator = arr.keys();
 
 console.log(iterator.next()); // { value: 0, done: false }
 console.log(iterator.next()); // { value: 1, done: false }
 console.log(iterator.next()); // { value: 2, done: false }
 console.log(iterator.next()); // { value: undefined, done: true }
  • 63. var arr = ['w', 'y', 'k', 'o', 'p'];
 var eArr = arr.values();
 console.log(eArr.next().value); // w
 console.log(eArr.next().value); // y
 console.log(eArr.next().value); // k
 console.log(eArr.next().value); // o
 console.log(eArr.next().value); // p
  • 64. var arr = ['a', 'b', 'c'];
 var eArr = arr.entries();
 
 console.log(eArr.next().value); // [0, 'a']
 console.log(eArr.next().value); // [1, 'b']
 console.log(eArr.next().value); // [2, 'c']
  • 65. function isPrime(element, index, array) {
 var start = 2;
 while (start <= Math.sqrt(element)) {
 if (element % start++ < 1) {
 return false;
 }
 }
 return element > 1;
 }
 
 console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
 console.log([4, 5, 8, 12].find(isPrime)); // 5
  • 66. function isPrime(element, index, array) {
 var start = 2;
 while (start <= Math.sqrt(element)) {
 if (element % start++ < 1) {
 return false;
 }
 }
 return element > 1;
 }
 
 console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
 console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
  • 68. ES6 SET • Lets you store unique values of any type • You can store primitive values or object references
  • 69. var mySet = new Set();
 
 mySet.add(1);
 mySet.add(5);
 mySet.add("some text");
 
 mySet.has(1); // true
 mySet.has(3); // false, 3 has not been added to the set
 mySet.has(5); // true
 mySet.has(Math.sqrt(25)); // true
 mySet.has("Some Text".toLowerCase()); // true
 
 mySet.size; // 3
 
 mySet.delete(5); // removes 5 from the set
 mySet.has(5); // false, 5 has been removed
 
 mySet.size; // 2, we just removed one value
  • 71. ES6 MAP • Simple key/value map • Any value (object or primitive value) can be used as either a key or a value
  • 72. var myMap = new Map();
 
 var keyObj = {},
 keyFunc = function () {},
 keyString = "a string";
 
 // setting the values
 myMap.set(keyString, "value associated with 'a string'");
 myMap.set(keyObj, "value associated with keyObj");
 myMap.set(keyFunc, "value associated with keyFunc");
 
 myMap.size; // 3
 
 // getting the values
 myMap.get(keyString); // "value associated with 'a string'"
 myMap.get(keyObj); // "value associated with keyObj"
 myMap.get(keyFunc); // "value associated with keyFunc"
 
 myMap.get("a string"); // "value associated with 'a string'"
 // because keyString === 'a string'
 myMap.get({}); // undefined, because keyObj !== {}
 myMap.get(function() {}) // undefined, because keyFunc !== function () {}
  • 78.