getting started with es6 : future of javascript

34
Future of javascript Getting Started with ES6 Mohammad Saeed Khan Naukri | FED

Upload: mohammad-saeed-khan

Post on 11-Apr-2017

603 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Getting started with ES6 : Future of javascript

Future of javascriptGetting Started with

ES6Mohammad Saeed Khan

Naukri | FED

Page 2: Getting started with ES6 : Future of javascript

Index● Motivation: Why should we use ES6 ?● ES6 Features● What to be covered next ?● How to use ES6 Features today ?

Transpilers ( source-to-source Compiler)

● Famous Build Tools

● Grunt Setup

● References

Page 3: Getting started with ES6 : Future of javascript

Why should we use ES6 ?● The syntax is simpler

● It's much easier and less error-prone to set up inheritance

hierarchies using the new syntax than with the old.

● The next-generation of JavaScript will bring a simpler and

friendlier syntax helping the learning process for

developers coming from other OOPs languages.

● Easy to build huge applications for the web in a scalable

and maintainable manner.

● JavaScript has blown up in popularity and is being used in

ways that were never imagined when it was first designed.

It’s time for JavaScript to grow up and become a “real”

language.

Page 4: Getting started with ES6 : Future of javascript

Evolution always comes with growing pains.

Time to speak up and try out what works for you.

Page 5: Getting started with ES6 : Future of javascript

ES6 Features● Let● Const● Class● Default Function Parameters● Collections● Sets● Maps● Destructuring● Object Destructuring● Rest Parameters● Spread operators● Iterators

Page 6: Getting started with ES6 : Future of javascript

● Template Strings● Promises● Modules ● module loader● Arrow functions● proxies● Symbols● Generators● enhanced object literals● weakmap + weakset● subclassable built-ins● math + number + string + array + object APIs● Array Comprehension● reflect api● tail calls

What to be covered in next session...

Page 7: Getting started with ES6 : Future of javascript

var jsFuture = "es6";(function() { if (!jsFuture) { let jsFuture = "es5"; } console.log(jsFuture);}());

Output: ???

var jsFuture = "es6";(function() { if (!jsFuture) { var jsFuture = "es5"; } console.log(jsFuture);}());

Output: ???

ES6ES5

Block Scoping with let

Page 8: Getting started with ES6 : Future of javascript

Const

Page 9: Getting started with ES6 : Future of javascript

● Class declarations are not hoisted

Classes

Let’s examine three kinds of methods that

you often find in class literals:-

● Prototypes having data properties is generally considered

an anti-pattern, so this just enforces a best practice.

● A class body can only contain methods(constructor, static

methods, prototype methods), but not data properties.

Page 10: Getting started with ES6 : Future of javascript

class team{ constructor(name, domain, work) { this.domain = domain; this.teamName = name; this.work = work; }

summary() { return this.domain + " " + this.teamName + " team is really doing " + this.work + " work"; }}

function team(name, domain, work) { this.domain = domain; this.teamName = name; this.work = work;

funiton sug()}

team.prototype.summary = function() { return this.domain + " " + this.teamName + " team is really doing " + this.work + " work";}

ES6ES5

var myInstance = new team("frontend", "Naukri", "awesome");console.log(myInstance.summary());

Class

Page 11: Getting started with ES6 : Future of javascript

Class Object

Page 12: Getting started with ES6 : Future of javascript

class Company extends team{ constructor(x, y, z, CompanyName) { super(x,y,z); this.CompanyName = CompanyName; }

summary() { return this.CompanyName+ " is a parent company of "+

this.domain + " but, " + this.domain+ " " +this.teamName+ " team is really doing

" +this.work+ " work"; }}var parentInst = new Company("frontend", "Naukri", "awesome",

"infoedge");console.log(parentInst.summary())

ES6 Class inheritance

Page 13: Getting started with ES6 : Future of javascript

Important Pointsconsole.log(parentInst instanceof Company); // true

console.log(parentInst instanceof team); // true

typeof team // 'function'

team() // TypeError: Classes can’t be function-called

foo(); // works, because ‘foo’ is hoistedfunction foo() {}

new Foo(); // ReferenceErrorClass Foo{}

function functionThatUsesBar(){new Bar();

}

functionThatUsesBar(); // ReferenceErrorclass Bar{};functionThatUsesBar(); // Ok

Page 14: Getting started with ES6 : Future of javascript

Class ExpressionsSimilarly to functions, there are two ways to define a

class:

class declarations and class expressions.

Also similarly to functions, the identifier of a class

expression is only visible within the expression:const myClass = class team{getClassName(){

return team.name }};

let inst = new myClass();console.log(inst.getClassName())console.log(team.name); // ReferenceError: team is not defined

Page 15: Getting started with ES6 : Future of javascript

Default Function ParametersWith default function parameters, we can always have function parameters as an option by setting some default values. The syntax for this feature in ES6 is extremely intuitive.

The default parameters are defined when the functions are defined.

function history(lang = "C", year = 1972) { return lang + " was created around the year " + year;}

console.log(history());

console.log(history('javascript', "1995"))

Let's have a look at the ES6 syntax below

Page 16: Getting started with ES6 : Future of javascript

Collections

ES6 offers new data structures previously not available in JavaScript

SET & MAP

Page 17: Getting started with ES6 : Future of javascript

Collection: SETSets are simple data structures that are similar to arrays,

but each value is unique.

var engines = new Set(); // create new Set engines.add("Gecko"); // add to Setengines.add("Trident");engines.add("Webkit");engines.add("Hippo");engines.add("Hippo"); // note that Hippo is added twice console.log("Browser engines include Gecko? " + engines.has("Gecko"));// trueconsole.log("Browser engines include Hippo? " + engines.has("Hippo"));// trueconsole.log("Browser engines include Indigo? " + engines.has("Indigo")); // false engines.delete("Hippo"); // delete itemconsole.log("Hippo is deleted. Browser engines include Hippo? " + engines.has("Hippo")); // false

Page 18: Getting started with ES6 : Future of javascript

Collection: MAP● Maps are quite similar to JavaScript object key-value pairs. Using a unique key,

we can retrieve the value. ● In ES6, the key can be any JavaScript data type and not just strings.

var es6 = new Map(); // create new Map es6.set("edition", 6); // key is stringes6.set(262, "standard"); // key is numberes6.set(undefined, "nah"); // key is undefined var hello = function() {console.log("hello");};es6.set(hello, "Hello ES6!"); // key is function

console.log( "Value of 'edition' exits? " + es6.has("edition") ); // trueconsole.log( "Value of 'year' exits? " + es6.has("years") ); // false

Page 19: Getting started with ES6 : Future of javascript

DestructuringIn programming languages, the term "destructuring" denotes pattern matching.

In ES6, we can do some pretty nifty pattern matching in arrays and objects that previously would have taken us more than one step.

Let's explore some of them

● Array destructuring

● Object destructuring

Page 20: Getting started with ES6 : Future of javascript

Array DestructuringWith array destructing, we can initialize(not declare) variables at once, or even swap them instead of having the conventional way of creating a var temp; //temporary variable.

var [ start, end ] = ["earth", "moon"] // initialize

console.log(start + " calling " + end); // earth calling moon [start, end] = [end, start]; // variable swapping

console.log(start + " calling " + end); // moon calling earth

Page 21: Getting started with ES6 : Future of javascript

Array Destructuring ...Destructuring also becomes a useful shorthand when returning multiple values from a function, as we do not need to wrap around an object anymore. Also, to skip certain variables, just leave the array element empty:

function equinox() { return [20, "March", 2013, 11, 02];}

var [date, month, , ,] = equinox();

console.log("This year's equinox was on " + date + month); // This year's equinox was on 20March

Page 22: Getting started with ES6 : Future of javascript

By destructuring, variables can also be initialized from an object that is returned from a function even with deeply nested objects. Also, just like the array patterns, we can skip the ones not needed. Here's the snippet of code that illustrates just this:

function equinox2() { return { date: 20, month: "March", year: 2013, time: { hour: 11, // nested minute: 2 } };}

Object destructuring

var { date: d, month: m, time : { hour: h} } = equinox2();// h has the value of the nested property while "year" and "minute" are skipped totally console.log("This year's equinox was on " + d + m + " at " + h); // This year's equinox was on 20March at 11

Page 23: Getting started with ES6 : Future of javascript

Rest ParametersIn ES6, rest parameters allows us to easily use a few fixed

parameters in a function, along with the rest of the trailing

and variable number of parameters.

We already use arguments, which is an array-like object

that defines the arguments passed to a function, but clearly

we cannot use the array function to manipulate these

arguments. With a clear syntax in ES6, it also moves the

intent of the developer into the syntax level with three

dots ... to denote a variable number of arguments.

Page 24: Getting started with ES6 : Future of javascript

function push(array, ...items) { // defining rest parameters with 3

dot syntax

items.forEach(function(item) { array.push(item); console.log( item ); });} // 1 fixed + 4 variable

parameters

var planets = [];

console.log("Inner planets of our Solar system are: " );

push(planets, "Mercury", "Venus", "Earth", "Mars"); // rest parameters

Page 25: Getting started with ES6 : Future of javascript

Spread operator

A spread operator is the opposite of rest parameters. When calling a function, we can pass in the fixed argument that is needed along with an array of a variable size with the familiar three dot syntax, to indicate the variable number of arguments.

Page 26: Getting started with ES6 : Future of javascript

// Spread operator "...weblink"function createURL (comment, path, protocol, subdomain, domain, tld) {

var shoutout = comment + ": " + protocol + "://" + subdomain + "." + domain + "." + tld + "/" + path; console.log( shoutout );} var weblink = ["hypertext/WWW/TheProject.html", "http", "info", "cern", "ch"], comment = "World's first Website"; createURL(comment, ...weblink ); // spread operator

In the example below, the function requires six separate arguments. When calling the function, the data is passed as an array with the spread operator. Let's see how the syntax looks, when calling the function with fixed arguments as well as a variable number of arguments:

Page 27: Getting started with ES6 : Future of javascript
Page 28: Getting started with ES6 : Future of javascript

Iterators→ for-ofvar planets = ["Mercury", "Venus", "Earth", "Mars"];for (let p of planets) { console.log(p); // Mercury, Venus, Earth, Mars} var engines = new Set(["Gecko", "Trident", "Webkit", "Webkit"]);for (var e of engines) { console.log(e); // Set only has unique values, hence Webkit shows only once} var es6 = new Map();es6.set("edition", 6);es6.set("committee", "TC39");es6.set("standard", "ECMA-262");for (var [name, value] of es6) { console.log(name + ": " + value);}

Page 29: Getting started with ES6 : Future of javascript
Page 30: Getting started with ES6 : Future of javascript

● Babel - Turn ES6+ code into vanilla ES5 with no runtime● Traceur compiler - ES6 features > ES5. Includes classes,

generators, promises, destructuring patterns, default parameters & more.

● es6ify - Traceur compiler wrapped as a Browserify v2 transform● babelify - Babel transpiler wrapped as a Browserify transform● es6-transpiler - ES6 > ES5. Includes classes, destructuring,

default parameters, spread● Square's es6-module-transpiler - ES6 modules to AMD or CJS● Facebook's regenerator - transform ES6 yield/generator functions

to ES5● Facebook's jstransform - A simple utility for pluggable JS

syntax transforms. Comes with a small set of ES6 -> ES5 transforms

● defs - ES6 block-scoped const and let variables to ES3 vars● es6_module_transpiler-rails - ES6 Modules in the Rails Asset

Pipeline● Some Sweet.js macros that compile from ES6 to ES5● Bitovi's transpile - Converts ES6 to AMD, CJS, and StealJS.

Transpilers ( source-to-source Compiler)

Page 31: Getting started with ES6 : Future of javascript

Famous Build Tools● Grunt● Webpack● Gulp ● Broccoli ● Brunch

Page 32: Getting started with ES6 : Future of javascript

Grunt Setup: convert ES6 to ES5 using bebel

Add below dependencies in package.json file and run: npm install

// package.json {

"babel-preset-es2015": "^6.1.18","grunt-babel": "^6.0.0","load-grunt-tasks": "^3.3.0”

}

or run:

npm install grunt-babel, babel-preset-es2015, load-grunt-tasks

babel: { options: { sourceMap: true, presets: ['es2015'] }, build: { files: [{ expand: true, // Enable dynamic expansion cwd: 'src/jass', // Src matches are relative to this path src: ['**/*.js'], // Actual patterns to match dest: 'src/j' }] } }

Page 34: Getting started with ES6 : Future of javascript

Thank you…

Any Query ?