├── .gitignore ├── LICENSE ├── README.md └── js ├── arrow-es6.js ├── binary-and-octal-es6.js ├── classes-es6.js ├── destructuring-es6.js ├── function-es6.js ├── generators-es6.js ├── loop-es6.js ├── map-es6.js ├── modules-es6.js ├── promises-es6.js ├── set-es6.js ├── spread-operator-es6.js ├── string-es6.js └── variable-es6.js /.gitignore: -------------------------------------------------------------------------------- 1 | test.html -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Ikrum Hossain 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ES6-in-code 2 | ECMAScript 6 features explained with code. 3 | 4 | ## Contribution 5 | Let's add some cool example and mark your contribution here. 6 | 7 | ## Code 8 | * [Variable](js/variable-es6.js) 9 | * [String](js/string-es6.js) 10 | * [Binary and Octal Literal](js/binary-and-octal-es6.js) 11 | * [Loop](js/loop-es6.js) 12 | * [Function](js/function-es6.js) 13 | * [Arrow Functions](js/arrow-es6.js) 14 | * [Generator Functions](js/generators-es6.js) 15 | * [Spread Operator](js/spread-operator-es6.js) 16 | * [Destructuring](js/destructuring-es6.js) 17 | * [Classes](js/classes-es6.js) 18 | * [Modules](js/modules-es6.js) 19 | * [Map and WeakMap](js/map-es6.js) 20 | * [Set and WeakSet](js/set-es6.js) 21 | * [Promises](js/promises-es6.js) 22 | 23 | # Note 24 | Before using ES6 features please check [ECMAScript 6 compatibility table](https://kangax.github.io/compat-table/es6/) 25 | -------------------------------------------------------------------------------- /js/arrow-es6.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Arrow function is the short form of regular function expressions. 3 | * Arrow functions bind this lexically 4 | * Arrow functions are also called "fat arrow" functions 5 | * Its allow you to write short and concise code 6 | * 7 | * 8 | * SYNTAX for ES6 Arrow functions 9 | * ------------------------------- 10 | * keyword 'function' is not required 11 | * arrow sign '=>' will be used between function parameter and function body 12 | * 13 | * (param1, param2, …, paramN) => { statements OR expression} 14 | * () => { statements } is equivalent to function(){statements} 15 | * 16 | * 17 | * References: 18 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions 19 | * http://tc39wiki.calculist.org/es6/arrow-functions/ 20 | * https://www.smashingmagazine.com/2015/10/es6-whats-new-next-version-javascript/ 21 | */ 22 | 23 | 24 | // A function with no parameters requires parentheses: 25 | var emptyFunction = () => {}; // arrow function 26 | var emptyFunction = function(){}; // equivalent regular function 27 | 28 | 29 | //Parentheses are optional for one parameter 30 | var value = x => x; // arrow function without parentheses 31 | var value = function(x){return x}; // regular function 32 | value(10); // 10 33 | 34 | 35 | 36 | // regular sum function 37 | var sum = function(x, y){ 38 | return x+y; 39 | } 40 | // sum function using 'fat arrow' 41 | var sum = (x,y)=>x+y; 42 | sum(10,10) // 20 43 | 44 | 45 | 46 | // use in array map 47 | let books = [{title: 'X', price: 10}, {title: 'Y', price: 15}]; 48 | var titles = books.map( item => item.title ); // very concise code using arrow function 49 | // ES5 equivalent: 50 | var titles = books.map(function(item) { 51 | return item.title; 52 | }); 53 | console.log(titles); // [X,Y] 54 | 55 | 56 | 57 | //Returning object literal. Requires Brackets. 58 | var myFunction = () => ({ "myProp" : 123 }); 59 | 60 | //ES5 equivalent: 61 | var myFunction = function() { 62 | return { "myProp" : 123 }; 63 | }; 64 | 65 | 66 | // anonymous functions 67 | var x_es6 = ()=>55() ; // x_es6 = 55; 68 | var x_es5 = (function(){return 55})(); // x_es5 = 55; 69 | 70 | var y_es6 = (x=>x*2)(10); // y_es6 = 20; 71 | var y_es5 = (function(x){return x*2})(10); // y_es5 = 20; -------------------------------------------------------------------------------- /js/binary-and-octal-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Binary and Octal Literals 3 | * 4 | * Two new numeric literal forms are added for binary (b) and octal (o). 5 | * So in ES6 its more easier to identify binary and octal numbers. 6 | */ 7 | 8 | // "0b" lets you create a number using binary of the number directly. 9 | var a = 0b11011101; 10 | console.log(a); //221 11 | console.log(0b111110111 === 503) // true 12 | 13 | // "0o" is a new way of creating a number using octal value in ES6. 14 | var b = 0o12; 15 | console.log(b); //10 16 | console.log(0o767 === 503); // true -------------------------------------------------------------------------------- /js/classes-es6.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | /** 4 | * JavaScript classes provide a much simpler and clearer syntax to create objects and deal with inheritance. 5 | * The bodies of class declarations and class expressions are executed in strict mode. 6 | * 7 | * To declare a class, you use the 'class' keyword 8 | * class ClassName{ } 9 | * 10 | *References: 11 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes 12 | * http://stackoverflow.com/questions/36099721/javascript-what-is-the-difference-between-function-and-class 13 | */ 14 | 15 | 16 | // Create a Class named 17 | class MyClass{ 18 | 19 | } 20 | 21 | /* 22 | * Constructor 23 | * 24 | * The constructor method is a special method for creating and initializing an object 25 | * There can only be one special method with the name "constructor" in a class. 26 | */ 27 | 28 | class Polygon { 29 | constructor(width, height) { // constructor method 30 | this._width = width; 31 | this._height = height; 32 | } 33 | } 34 | 35 | 36 | /** 37 | * 38 | * Above example can be achieved by the following function 39 | */ 40 | function PolygonFunc(width, height) { 41 | this._width = width; 42 | this._height = height; 43 | } 44 | 45 | 46 | /** 47 | * 48 | * What is the difference between Function and Class 49 | * 50 | * JavaScript classes are syntactical sugar over JavaScript's existing prototype-based inheritance 51 | * Classes are in fact "special functions" 52 | * 53 | * In terms of syntax and uses Class is different from Functions 54 | * 55 | * 56 | * DEFINE CLASS BODY 57 | ********************************************************* 58 | * Constructor 59 | * ----------- 60 | * A special function named 'constructor' 61 | * 62 | * Member Methods 63 | * -------------- 64 | * property( parameters… ) {}, 65 | * 66 | * 67 | * ES5 Getter Setters 68 | * ------------------ 69 | * get property() {}, 70 | * set property(value) {} 71 | * 72 | * 73 | * Static methods 74 | * -------------- 75 | * Define static methods using 'static' keyword 76 | * Static methods are called without creating the instance of the class 77 | * Those methods are often used to create utility functions for an application. 78 | */ 79 | 80 | class Car { 81 | // constructor 82 | constructor(owner) { 83 | this._owner = owner; 84 | this._distance = 0; 85 | this._destination = ""; 86 | } 87 | 88 | // member method 89 | move(){ 90 | this._distance += 1; 91 | } 92 | 93 | // getter setters 94 | get destination(){ 95 | return this._destination; 96 | } 97 | set destination(location){ 98 | this._destination = location; 99 | } 100 | get owner(){ 101 | return this._owner; 102 | } 103 | get distance(){ 104 | return this._distance; 105 | } 106 | 107 | // Static methods 108 | static status(){ 109 | return "ACTIVE"; 110 | } 111 | } 112 | 113 | var car = new Car("John"); 114 | console.log(car.owner); // John 115 | 116 | console.log(car.destination); // empty string 117 | car.destination = "Town Hall"; // setting the destination 118 | console.log(car.destination); // TownHall 119 | 120 | console.log(car.distance); // 0 121 | car.move(); // calling member method 122 | console.log(car.distance); // 1 123 | 124 | // use of static method 125 | console.log(car.status()) // ERROR , static functions are not a member of the car object 126 | console.log(Car.status()) // ACTIVE, call static function directly ClassName.yourStaticFunction(); 127 | 128 | 129 | 130 | /** 131 | * Hoisting 132 | * 133 | * function declarations are hoisted and class declarations are not. 134 | */ 135 | var p = new Box(); // ReferenceError, can't be used before declaration 136 | class Box {} 137 | 138 | /* 139 | * Only methods to be declared inside the class body. 140 | */ 141 | class notWorking { 142 | var privateVar; // ERROR 143 | return 1; // ERROR 144 | }; -------------------------------------------------------------------------------- /js/destructuring-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * The destructuring assignment syntax allow you to extract data from arrays or objects 3 | * 4 | * References: 5 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment 6 | */ 7 | 8 | 9 | /* 10 | * Array destructuring 11 | */ 12 | 13 | (function(){ 14 | 15 | var a, b, rest; 16 | [a, b, ...rest] = [1, 2, 3, 4, 5] 17 | console.log(a) // 1 18 | console.log(b) // 2 19 | console.log(rest) // [3, 4, 5] 20 | 21 | var foo = ["one", "two", "three"]; 22 | var [one, two, three] = foo; 23 | console.log(one); // "one" 24 | console.log(two); // "two" 25 | console.log(three); // "three" 26 | 27 | })(); 28 | 29 | /* 30 | * We can assign a default value if the array index is undefined 31 | */ 32 | (function(){ 33 | var a, b; 34 | [a=5, b=7] = [1]; 35 | console.log(a); // 1 36 | console.log(b); // 7 37 | })(); 38 | 39 | /* 40 | * Swapping variables 41 | */ 42 | 43 | (function(){ 44 | var a = 1; 45 | var b = 3; 46 | 47 | [a, b] = [b, a]; 48 | console.log(a); // 3 49 | console.log(b); // 1 50 | })(); 51 | 52 | /* 53 | * function returns multiple values and assign using array destructuring feature 54 | * Here we are ignoring 2 and 6 array indexes 55 | */ 56 | 57 | (function(){ 58 | function myFunction(){ 59 | return [1,2,3,4,5,6]; 60 | } 61 | 62 | var a,b,c,d,e,f; 63 | [a,,c,d,e] = myFunction(); 64 | console.log(a,b,c,d,e,f); // 1 undefined 3 4 5 undefined 65 | })(); 66 | 67 | 68 | 69 | /* 70 | * Object destructuring 71 | */ 72 | 73 | var obj = {name: "john", age: 45}; 74 | var {name, age} = obj; 75 | 76 | console.log(name); // john 77 | console.log(age); // 45 -------------------------------------------------------------------------------- /js/function-es6.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * ES6 provides a new syntax to initialize parameters if they were not explicitly supplied 4 | * 5 | * 6 | * References 7 | * http://tc39wiki.calculist.org/es6/default-parameter-values/ 8 | * http://qnimate.com/post-series/ecmascript-6-complete-tutorial/ 9 | */ 10 | 11 | 12 | /* 13 | * In ES5 we used to check undefined variables and set a default value 14 | */ 15 | 16 | function getData(options){ 17 | options = options || {}; // set a default value to {} 18 | } 19 | getData(); // options parameter is not passed 20 | 21 | /* OR */ 22 | function multiply(a, b){ 23 | var b = typeof b !== 'undefined' ? b : 1; 24 | console.log( a*b ) // 5 25 | } 26 | multiply(5); 27 | 28 | 29 | 30 | /* 31 | * In ES6 you can define default values to function parameters 32 | */ 33 | 34 | function divide(a,b=1){ 35 | console.log( a/b ); // 5 36 | } 37 | divide(5); 38 | 39 | 40 | 41 | /* 42 | * passing undefined is considered as missing an argument. 43 | * But null is being passed as a value 44 | */ 45 | (function(a = 1, b = 2, c = 3, d=10){ 46 | console.log(a, b, c, d); // Output "1 7 null 10" 47 | 48 | })(undefined,7,null); 49 | 50 | 51 | 52 | /* 53 | * Defaults can also be expressions 54 | */ 55 | 56 | (function(x = 1, y = 2, z = 3 + 5){ 57 | console.log(x, y, z); // Output "6 7 8" 58 | })(6,7); -------------------------------------------------------------------------------- /js/generators-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * JavaScript Generators 3 | * 4 | * ECMAScript 6 specification introduced a new JavaScript feature called as JavaScript Generators. 5 | * Generators are functions which can be exited and later re-entered. 6 | * 'yield' keyword and function*() syntax together make JS Generators. 7 | * 8 | * 9 | * References 10 | * http://qnimate.com/javascript-yield-keyword-and-function-syntax/ 11 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function* 12 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/yield 13 | */ 14 | 15 | /* 16 | * Generator function 17 | * 18 | * The function* declaration (function keyword followed by an asterisk) defines a generator function 19 | * It returns a Generator object. 20 | * 21 | * 22 | * yield 23 | * The yield keyword is used to pause and resume a generator function 24 | */ 25 | 26 | function* getIds() 27 | { 28 | yield 1; // return 1 and pause 29 | yield 3; // return 3 and pause 30 | yield 5; // return 5 and pause 31 | yield 7; // return 7 and pause 32 | } 33 | 34 | var ids = getIds(); // return generator object 35 | 36 | console.log(ids.next()); // { value: 1, done: false } 37 | console.log(ids.next()); // { value: 3, done: false } 38 | console.log(ids.next()); // { value: 5, done: false } 39 | console.log(ids.next()); // { value: 7, done: false } 40 | console.log(ids.next()); // { value: undefined, done: true } 41 | 42 | // The yield* expression is used to delegate to another generator or iterable object. 43 | function* myGenerator() { 44 | yield* [1, 2, 3]; 45 | return "foo"; 46 | } 47 | 48 | var gen = myGenerator(); 49 | console.log(gen.next()); 50 | console.log(gen.next()); 51 | console.log(gen.next()); 52 | console.log(gen.next()); // myGenerator() returned { value: "foo", done: true } at this point 53 | -------------------------------------------------------------------------------- /js/loop-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * for...of Loop 3 | * for(value of array){ } 4 | */ 5 | 6 | 7 | //Iterating over an Array 8 | (function(){ 9 | let myArray = [1, 2, 3]; 10 | for (let value of myArray) { 11 | console.log(value); 12 | // 1 13 | // 2 14 | // 3 15 | } 16 | })(); 17 | 18 | 19 | // Iterating over a String 20 | (function(){ 21 | let myString = "abc"; 22 | for (let value of myString) { 23 | console.log(value); 24 | } 25 | // "a" 26 | // "b" 27 | // "c 28 | })(); 29 | 30 | 31 | /* 32 | * Difference between for...of and for...in 33 | * 34 | * for..of takes the value from the iterator and for..in takes the index 35 | * When you need only the item for the iterator you can use for..of loop 36 | * If index or key is required then you could use regular for loop or for..in loop 37 | */ 38 | 39 | // when index is required, or you want to use object like associative array 40 | (function(){ 41 | var opts = { 42 | size: 20, 43 | flag: "OK" 44 | }; 45 | for (let key in opts){ 46 | // index is required 47 | if(key == "size"){ 48 | // do something with key 49 | } 50 | 51 | // use like associative array 52 | console.log( opts[key] ); 53 | } 54 | })(); 55 | 56 | // when index is not required, we just need the value 57 | (function(){ 58 | var foo = ["a","b", "c"]; 59 | for(let item of foo){ 60 | console.log(item); 61 | //a 62 | //b 63 | //c 64 | } 65 | })(); 66 | -------------------------------------------------------------------------------- /js/map-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Map 3 | * 4 | * Map is a key/value data structure in ES6. It provides a better data structure to be used for hash-maps. 5 | * 6 | * References 7 | * https://ponyfoo.com/articles/es6-maps-in-depth 8 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map 9 | */ 10 | 11 | // Create a map object 12 | var map = new Map(); 13 | // Use map.set(key, value) to add entries 14 | map.set('max_size', 20); 15 | map.set('max_speed', 150); 16 | map.set('model', "Primo X3"); 17 | map.set('info', { description: 'a long description of the model.', specifications: [] }); 18 | 19 | /* number of key/value pairs in the Map object. */ 20 | console.log(map.size); // Output 4 21 | 22 | /* get the value associated to the key */ 23 | console.log(map.get('max_speed')); // output 150 24 | 25 | /* update/override the existing key/value */ 26 | map.set('max_speed', 220); 27 | console.log(map.get('max_speed')); // output 220 28 | 29 | /* Delete key */ 30 | map.set('max_speed'); 31 | console.log(map.get('max_speed')); // output undefined 32 | 33 | /* check if the key exists */ 34 | console.log(map.has("unknown_key")); // output false 35 | 36 | /* 37 | * A Map object iterates its elements in insertion order 38 | * a for...of loop returns an array of [key, value] for each iteration. 39 | */ 40 | for(let item of map){ 41 | console.log(item); 42 | 43 | /* Output 44 | ["max_size", 20] 45 | ["max_speed", undefined] 46 | ["model", "Primo X3"] 47 | ["info", Object] 48 | */ 49 | } 50 | 51 | 52 | /* 53 | * Difference between Map and array 54 | * 55 | * One of the important differences is also that you're able to use anything for the keys. 56 | * You're not just limited to primitive values like symbols, numbers, or strings, 57 | * but you can even use functions, objects and dates – too. 58 | * Keys won't be casted to strings like with regular objects, either. 59 | */ 60 | 61 | var myMap = new Map() 62 | myMap.set(new Date(), function today () {}); 63 | myMap.set(() => 'key', { pony: 'foo' }); 64 | myMap.set(Symbol('items'), [1, 2]); 65 | 66 | 67 | 68 | /* 69 | * WeakMap 70 | * "WeakMaps" provides leak-free object-key’d side tables. 71 | * "Map" references are strong pointer whereas "WeakMap" references are weak pointers. 72 | */ 73 | 74 | let weakmap = new WeakMap(); 75 | let foo = { foo: 'bar' }; 76 | weakmap.set(foo, 10); 77 | console.log(weakmap.get(foo)); // bar 78 | foo = {foo: 'new_value'}; 79 | console.log(weakmap.get(foo)); // undefined 80 | 81 | 82 | // “WeakMap” keys cannot be primitive types 83 | weakmap.set(10, 55); //throws invalid type error -------------------------------------------------------------------------------- /js/modules-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Modules 3 | * Module is a completely new feature of ES6 4 | * A JavaScript module is a file that exports something for other modules to consume. 5 | * 6 | * Modules are just a way of packaging related JavaScript code in its own scope 7 | * which can be consumed by other JavaScript programs. 8 | * Using 'import' and 'export' keyword we can export some functionality for other modules to import 9 | * 10 | * 11 | * CommonJS 12 | * CommonJS is a non-browser JavaScript specification for creating modules. 13 | * CommonJS is not available for browser JavaScript. It's mostly used in NodeJS. 14 | * Now CommonJS features has been introduced in the new javascript(ES6) 15 | * 16 | * 17 | * References: 18 | * https://strongloop.com/strongblog/an-introduction-to-javascript-es6-modules/ 19 | * https://github.com/lukehoban/es6features 20 | */ 21 | 22 | 23 | /* 24 | * Default Exports 25 | * Every module can have one, and only one default export 26 | * Default export can be imported without specifying variable name. 27 | */ 28 | 29 | // hello-world.js 30 | export default function() {} 31 | 32 | // main.js 33 | import helloWorld from './hello-world'; 34 | helloWorld(); 35 | 36 | 37 | 38 | 39 | /* 40 | * Default Exports 41 | * A module can have any number of named exports of any type. 42 | * You need to specify name of the variable you wish to export and use the same name to import it 43 | */ 44 | 45 | 46 | // math.js 47 | const PI = 3.14; 48 | const value = 42; 49 | export {PI, value}; 50 | /* You can also change the export name without renaming the original variable */ 51 | export {value as THE_ANSWER}; 52 | 53 | 54 | /* 55 | * Import 56 | * use * to import all exports of the module 57 | * Don't need to use file extension( *.js), just specify the path in require() 58 | * 59 | */ 60 | 61 | // single import 62 | import PI from './math'; 63 | 64 | // Multiple import 65 | import {PI, value} from './math'; 66 | console.log(PI, value); // Output: 3.14 42 67 | 68 | // Import all 69 | import * as iMath from './math'; 70 | console.log(iMath.PI); 71 | console.log(iMath.value); 72 | console.log(iMath.THE_ANSWER); 73 | 74 | 75 | /* 76 | * Imported Variables Are Read-only 77 | * 78 | * 79 | * No matter what kind of declaration is being exported from a module, 80 | * imported variables are always read-only. 81 | * You can, however, change an imported object's properties. 82 | */ 83 | 84 | 85 | // module.js 86 | export let count = 0; 87 | export const table = {foo: 'bar'}; 88 | 89 | // main.js 90 | import {count, table} from './module'; 91 | 92 | table.foo = 'Bar'; // OK 93 | count++; // read-only error 94 | 95 | 96 | 97 | /* 98 | * A bigger example 99 | * 100 | * Consider the following folder structure for your projects 101 | 102 | Project: 103 | controllers/ 104 | - userController.js 105 | - authenticate.js 106 | 107 | utils/ 108 | - tokenizer.js 109 | 110 | main.js 111 | */ 112 | 113 | // tokenizer.js 114 | export function generateToken(){ // exporting tokenizer function 115 | return Math.random().toString(36).substring(7); 116 | } 117 | 118 | 119 | // controllers/authController.js 120 | var tokenizer = require('../utils/tokenizer'); // importing tokenizer module 121 | 122 | export default function(username, password){ 123 | /* do something with username and password*/ 124 | return tokenizer.generateToken(); // calling generateToken of tokenizer.js 125 | } 126 | 127 | // main.js 128 | var authenticate = require('./controllers/authenticate'); // importing authenticate module 129 | console.log( authenticate("myUserName", "myPassword") ); // Output: A random token for authentication 130 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /js/promises-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Promises 3 | * 4 | * Promises are a library for asynchronous programming. 5 | * A Promise represents an operation that hasn't completed yet, but is expected in the future. 6 | * Promises are used in many existing JavaScript libraries. 7 | * 8 | * Syntax 9 | * new Promise(function(resolve, reject) { ... }); 10 | * 11 | * References 12 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 13 | * https://github.com/lukehoban/es6features 14 | */ 15 | 16 | 17 | /* 18 | * States of a promise 19 | * 20 | * pending: initial state, not fulfilled or rejected. 21 | * fulfilled: meaning that the operation completed successfully. 22 | * rejected: meaning that the operation failed. 23 | */ 24 | 25 | var fetchData = function(userid){ 26 | return new Promise(function(resolve, reject){ 27 | // async task 28 | setTimeout(function(){ 29 | if(userid == 1) 30 | resolve({message: "Data successfully returned"}); 31 | else 32 | reject({error: "Document not found", status: 404}) 33 | }, 100); 34 | }); 35 | } 36 | 37 | fetchData(1).then(function(data){ 38 | console.log(data); // {message: "Data successfully returned"} 39 | }); 40 | 41 | fetchData("invalid text").then(function(data){ 42 | console.log(data); // won't execute 43 | }).catch(function(err){ 44 | console.log(err); // {error: "Document not found", status: 404} 45 | }); 46 | 47 | 48 | -------------------------------------------------------------------------------- /js/set-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Set 3 | * 4 | * JavaScript "Set" object is a collection of unique keys. Keys are object references or primitive types. 5 | * Similar to Map, but not quite the same 6 | * Set doesn't have keys, there's only values 7 | * Sets can't have duplicate values because the values are also used as keys 8 | * 9 | * References 10 | * http://qnimate.com/javascript-set-object/ 11 | * http://qnimate.com/difference-between-set-and-weakset-in-javascript/ 12 | * http://stackoverflow.com/questions/30556078/ecmascript-6-what-is-weakset-for 13 | * http://www.sitepoint.com/preparing-ecmascript-6-set-weakset/ 14 | */ 15 | 16 | 17 | //create a set 18 | var set = new Set(); 19 | 20 | //add keys to the set 21 | set.add({name: "John"}); 22 | set.add(10); 23 | set.add("foo"); 24 | 25 | //check if a provided key is present 26 | console.log(set.has("foo")); 27 | 28 | // get the values of the set 29 | console.log(set.values()); 30 | /* output 31 | * 0:object 32 | * 1:10 33 | * 2:"foo" 34 | */ 35 | 36 | //loop through the keys in an set 37 | for(var i of set){ 38 | console.log(i); 39 | /* Output 40 | * Object {name: "John"} 41 | * 10 42 | * foo 43 | */ 44 | } 45 | 46 | //delete a key 47 | set.delete("foo"); 48 | 49 | //create a set from array values 50 | var mySet = new Set([1, 2, 3, 4, 5]); 51 | 52 | //size of set 53 | console.log(mySet.size); //5 54 | 55 | 56 | /* 57 | * WeakSet 58 | * 59 | * Much like with WeakMap and Map 60 | * You can only .add, .has, and .delete values from a WeakSet. 61 | * 62 | * WeakSet has only three key functionalities: 63 | * Weakly link an object into the set 64 | * Remove a link to an object from the set 65 | * Check if an object has already been linked to the set 66 | */ 67 | 68 | //cannot be created from array 69 | var weakset = new WeakSet(); 70 | 71 | var obj = {name: 'John'}; 72 | 73 | // Adds an object to the set 74 | weakset.add(obj); 75 | /* 76 | * Checks whether the Object {name: 'John Doe'} exists in the weak set. 77 | * Prints "false" because, although it has same values and properties, they are different objects 78 | */ 79 | console.log(weakset.has({name: 'John'})); // false 80 | console.log(weakset.has(obj)); // true 81 | console.log(weakset.size);//undefined 82 | 83 | //you can’t iterate over WeakSet 84 | //doesn't execute throws error 85 | for(var i of weakset){ 86 | console.log(i); 87 | } 88 | 89 | // we can’t use primitive values. 90 | var fooSet = new WeakSet() 91 | fooSet.add(Symbol()) 92 | // TypeError: invalid value used in weak set -------------------------------------------------------------------------------- /js/spread-operator-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Spread Operator 3 | * 4 | * The spread operator (...) is a very convenient syntax to expand elements 5 | * of an array in specific places, such as arguments in function calls. 6 | * 7 | * 8 | * 9 | * References 10 | * http://qnimate.com/javascript-operator/ 11 | * https://www.smashingmagazine.com/2015/10/es6-whats-new-next-version-javascript/ 12 | */ 13 | 14 | 15 | // uses in variables 16 | let values = [1, 2, 4]; 17 | let some = [...values, 8]; // [1, 2, 4, 8] 18 | let more = [...values, 8, ...values]; // [1, 2, 4, 8, 1, 2, 4] 19 | 20 | /* 21 | * uses of spread operator in function parameter 22 | * args is an array holding the arguments passed to the function 23 | */ 24 | (function(...args){ 25 | console.log(args); // [1,2,3] 26 | })(1, 2, 3); 27 | 28 | (function(a, b, ...args){ 29 | console.log(a); // 1 30 | console.log(b); // 5 31 | console.log(args); // [7,9] 32 | console.log(args.length); // 2 33 | })(1, 5, 7, 9); //"args" holds only 7 and 9 34 | 35 | -------------------------------------------------------------------------------- /js/string-es6.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Template literals 3 | * 4 | * Template literals provide a clean way to create strings and perform string interpolation. 5 | * The syntax based on the dollar sign and curly braces ${..}. 6 | * Template literals are enclosed by `backticks`. 7 | * 8 | * 9 | * References 10 | * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals 11 | * https://www.smashingmagazine.com/2015/10/es6-whats-new-next-version-javascript/ 12 | */ 13 | /* 14 | * Syntax 15 | * 16 | * `string text` 17 | * 18 | * `string text line 1 19 | * string text line 2` 20 | * 21 | * 22 | * `string text ${expression} string text` 23 | */ 24 | 25 | // Multi-line strings 26 | var welcomeMsg = `Hello dear, 27 | You can see me at second line at your output`; 28 | 29 | console.log(welcomeMsg) 30 | 31 | 32 | // String interpolation 33 | var name = "John", 34 | age = 24, 35 | hobby = "Programming"; 36 | 37 | var story = ` 38 | My name is ${name}. 39 | I am ${age} years old and I love ${hobby} 40 | 41 | Regards 42 | THE LAST LINE 43 | `; 44 | console.log(story); 45 | 46 | // ES5 equivalent 47 | var es5_story = "My name is "+ name +"\nI am "+age+" years old and I love "+hobby+"\n\n"+"Regards\nTHE LAST LINE"; 48 | console.log("\n\nES5 equivalent:"); 49 | console.log(es5_story); 50 | 51 | 52 | /* 53 | * String Methods 54 | * 55 | * A couple of convenience methods have been added to the String prototype. 56 | * Here is the simple demonstration: 57 | */ 58 | 59 | 60 | // Most of them basically eliminate some workarounds with the indexOf() method to achieve the same: 61 | 'my string'.startsWith('my'); //true 62 | 'my string'.endsWith('my'); // false 63 | 'my string'.includes('str'); // true 64 | 65 | // create a repeating string 66 | 'my '.repeat(3); // 'my my my ' -------------------------------------------------------------------------------- /js/variable-es6.js: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * ES6 has introduced two new keyword 'let' and 'const' for declaring variables 4 | * So basically 'let' and 'const' are new alternative of 'var' for declaring variables 5 | */ 6 | 7 | 8 | /** 9 | * let 10 | * 11 | * let declares local variable for the nearest enclosing block 12 | * let has been in Firefox for a long time and is now a part of ES6. 13 | * 14 | * References: 15 | * https://github.com/sgaurav/understanding-es6/blob/master/let.js 16 | */ 17 | 18 | (function (myArray) { 19 | for(let i = 0; i