Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Getting started with ES6 : Future of javascript

683 views

Published on

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

Published in: Technology

Getting started with ES6 : Future of javascript

  1. 1. Future of javascript Getting Started with ES6 Mohammad Saeed Khan Naukri | FED
  2. 2. 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
  3. 3. 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.
  4. 4. Evolution always comes with growing pains. Time to speak up and try out what works for you.
  5. 5. ES6 Features ● Let ● Const ● Class ● Default Function Parameters ● Collections ● Sets ● Maps ● Destructuring ● Object Destructuring ● Rest Parameters ● Spread operators ● Iterators
  6. 6. ● 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...
  7. 7. 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
  8. 8. Const
  9. 9. ● 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.
  10. 10. 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
  11. 11. Class Object
  12. 12. 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
  13. 13. Important Points console.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 hoisted function foo() {} new Foo(); // ReferenceError Class Foo{} function functionThatUsesBar(){ new Bar(); } functionThatUsesBar(); // ReferenceError class Bar{}; functionThatUsesBar(); // Ok
  14. 14. Class Expressions Similarly 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
  15. 15. Default Function Parameters With 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
  16. 16. Collections ES6 offers new data structures previously not available in JavaScript SET & MAP
  17. 17. Collection: SET Sets 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 Set engines.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")); // true console.log("Browser engines include Hippo? " + engines.has("Hippo")); // true console.log("Browser engines include Indigo? " + engines.has("Indigo")); // false engines.delete("Hippo"); // delete item console.log("Hippo is deleted. Browser engines include Hippo? " + engines.has("Hippo")); // false
  18. 18. 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 string es6.set(262, "standard"); // key is number es6.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") ); // true console.log( "Value of 'year' exits? " + es6.has("years") ); // false
  19. 19. Destructuring In 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
  20. 20. Array Destructuring With 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
  21. 21. 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
  22. 22. 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
  23. 23. Rest Parameters In 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.
  24. 24. 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
  25. 25. 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.
  26. 26. // 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:
  27. 27. Iterators→ for-of var 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); }
  28. 28. ● 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)
  29. 29. Famous Build Tools ● Grunt ● Webpack ● Gulp ● Broccoli ● Brunch
  30. 30. 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' }] } }
  31. 31. Resources Brendan Eich Addy Osmani Ariya Hidayat Nicholas Zakas Axel Rauschmayer Brandon Benvie ECMAScript 6 support in Mozilla Draft specification for ES.next The Future of JavaScript, a video by Dave Herman ECMAScript 6 - The Refined Parts (video and slides) by Kit Cambridge Latest Tweets on ES mailing list es6 - my fav parts ES6 has proper tail calls Power of Getters ECMAScript 6 ES6 deep Dive by Dave Herman Classes https://github.com/addyosmani/es6-tools ... in depth..
  32. 32. Thank you… Any Query ?

×