Introduction to ES6 By Nilesh Jayanandana
Lecture 1 Introduction and prerequisites
Welcome to the JS World!
What is ECMAScript? ECMAScript is the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016. Don’t worry, ES7 and ES6 are basically similar except for a few addons.
Lets setup our Environment Softwares You need, NodeJS → Node and NPM latest versions Visual Studio Code → My favourite Editor
What is Node and npm? NodeJS is a platform built on Chrome’s JavaScript Engine V8. Introduced by Ryan Dhal in 2008. npm → Node Package Manager nvm → Node Version Manager Dependency Manager for your JS Libraries.
NPM npm init → Initialize npm package.json npm install <package name> --save → normal dependencies Use --save-dev for dev dependencies What are dev-dependencies? Dependencies needed for development, building and testing Introduce Shrinkwrap → lockdown dependancies
Demo → NodeJS and NPM
Let’s dive into ES6!
What’s new? Arrow Functions, enhanced collections, generators and more. Code is very clean intuitive and well designed. Transpiling → convert ES6 to vanilla JS Reads Code in one language and produces code in another language Tools needed → webapck, babel Alternatives → Gulp or any other task runner
Demo - Babel
Demo - Setting Up webpack
Lecture 2 ES6 Essentials - Part 1
Assignment In ES6 Let vs const Var limit = 100 → vanilla js Let limit = 100 or const limit = 100 Let Can change the value Why have let when u can have var? → explained in the block scoping section. Const Constant. Cannot re-assign.
ES6 Assignment Demo
Block Scoping Local Scope vs Global Scope {...} Print ( ) { console.log(“print something”) }; Can define any variable we want in the scope that no other object can access
Block Scope Demo
Template Literals Strings with embedded expressions Vanilla JS → var name = “Nilesh”; “Hello My name is ”+ name; ES6 → `Hello My name is ${name} `; BackTicks! Eases string update and concatenation
Operating and Destructuring Assignment Spread Operator : { … } Rest Parameter : function( … ){ } Destructuring Arrays and Objects
Demo
Lecture 3 ES6 Essentials part 2
Methods and modules Arrow functions Anonymous functions Helper Methods Map method → creates new array calling functions on individual elements of original array Filter method → create new array based on original array depending on some test given for each element. Modules → split code into unique files based on relevant data Export and Import
Demo - Arrow Functions
Demo - Helper Methods
Demo - Modules
Lecture 4 Classes and Prototypes
Classes Relate to each other through Inheritance Acts like a OOP class but not really! → explained in prototypes Defined with the word class and has constructors Polymorphism → method overloading, overriding Inheritance → extends keyword Encapsulation → this keyword Supports static methods
Classes - Demo
Prototypes Classes vs Prototypes OOP → Objects or classes hold relevant data that interact with each other. Java, Ruby, Python etc support OOP Classes we spoke about previously are not real classes like in OOP model Javascript supports a prototypal inheritance model
Prototypes Ctd... Under the hood Classes are just extractions of js prototypes. So we are not creating objects like how ruby or java does with their OOP models. But ES6 syntax enables us to work with classes just like how we would work with a OOP supported language model.
What is a prototype? A prototype is a characteristic that every object in javascript has. Tells us a very specific characteristic about that object Every prototype has information about their parent prototype. It reveals the parent of an object All objects except object literals Date, Array etc has a prototype At the very top of this chain is the object Prototype which has object properties
Demo - Prototypes
Lecture 5 Data Structures in ES6
Data Structures - The Set Algorithms solve various problems in different running times Algorithms differ in their efficiency with resource usage The Set → stores unique values Advantageous in storing no duplicates. .add() .has() etc
Data Structures - The Map The Map → has keys and values like objects Difference? → Beat objects with superior keys and size property.
Demo - Data Strucutres
Lecture 6 Closures
Closures Important concept in JS Remember their creation environment and can reference independent variables within that environment. → uses lexical scoping Lexical scoping → refers to the idea that JS and our program keeps track of the location of a variable to understand where it can be accessed. Enable function factories Enable private data
Demo
Lecture 7 Generators
Generators Breaks the typical run to complete model in functions Generators can pause, and resume functions with yield and next() Construct controlled flow functions with simplified iterators. function* is the syntax
Demo
Lecture 8 Asynchronous Programming and promises
Synchronous vs Asynchronous Synchronous programming run in sequence without blocking Asynchronous diverts blocking to event handlers Promises handle Async in ES6 Promises exist in 3 states → Pending, Fulfilled and Rejected
Demo
Lecture 9 ES7 and ES8
What’s changed? Not much was added from ES6 ES6 was the major upgrade Additional Minor functionality was included 2**5 → Math.pow(2,5); Async Functions → still a proposal
Thank You
Q & A

Introduction to Ecmascript - ES6

  • 1.
    Introduction to ES6 ByNilesh Jayanandana
  • 2.
  • 3.
    Welcome to theJS World!
  • 4.
    What is ECMAScript? ECMAScriptis the name of the international standard that defines JavaScript. ES6 → ECMAScript 2015. Latest ECMAScript version is ES7 which is ECMAScript 2016. Don’t worry, ES7 and ES6 are basically similar except for a few addons.
  • 5.
    Lets setup ourEnvironment Softwares You need, NodeJS → Node and NPM latest versions Visual Studio Code → My favourite Editor
  • 6.
    What is Nodeand npm? NodeJS is a platform built on Chrome’s JavaScript Engine V8. Introduced by Ryan Dhal in 2008. npm → Node Package Manager nvm → Node Version Manager Dependency Manager for your JS Libraries.
  • 7.
    NPM npm init →Initialize npm package.json npm install <package name> --save → normal dependencies Use --save-dev for dev dependencies What are dev-dependencies? Dependencies needed for development, building and testing Introduce Shrinkwrap → lockdown dependancies
  • 8.
  • 9.
  • 10.
    What’s new? Arrow Functions,enhanced collections, generators and more. Code is very clean intuitive and well designed. Transpiling → convert ES6 to vanilla JS Reads Code in one language and produces code in another language Tools needed → webapck, babel Alternatives → Gulp or any other task runner
  • 11.
  • 12.
    Demo - SettingUp webpack
  • 13.
  • 14.
    Assignment In ES6 Letvs const Var limit = 100 → vanilla js Let limit = 100 or const limit = 100 Let Can change the value Why have let when u can have var? → explained in the block scoping section. Const Constant. Cannot re-assign.
  • 15.
  • 16.
    Block Scoping Local Scopevs Global Scope {...} Print ( ) { console.log(“print something”) }; Can define any variable we want in the scope that no other object can access
  • 17.
  • 18.
    Template Literals Strings withembedded expressions Vanilla JS → var name = “Nilesh”; “Hello My name is ”+ name; ES6 → `Hello My name is ${name} `; BackTicks! Eases string update and concatenation
  • 19.
    Operating and DestructuringAssignment Spread Operator : { … } Rest Parameter : function( … ){ } Destructuring Arrays and Objects
  • 20.
  • 21.
  • 22.
    Methods and modules Arrowfunctions Anonymous functions Helper Methods Map method → creates new array calling functions on individual elements of original array Filter method → create new array based on original array depending on some test given for each element. Modules → split code into unique files based on relevant data Export and Import
  • 23.
    Demo - ArrowFunctions
  • 24.
  • 25.
  • 26.
  • 27.
    Classes Relate to eachother through Inheritance Acts like a OOP class but not really! → explained in prototypes Defined with the word class and has constructors Polymorphism → method overloading, overriding Inheritance → extends keyword Encapsulation → this keyword Supports static methods
  • 28.
  • 29.
    Prototypes Classes vs Prototypes OOP→ Objects or classes hold relevant data that interact with each other. Java, Ruby, Python etc support OOP Classes we spoke about previously are not real classes like in OOP model Javascript supports a prototypal inheritance model
  • 30.
    Prototypes Ctd... Under thehood Classes are just extractions of js prototypes. So we are not creating objects like how ruby or java does with their OOP models. But ES6 syntax enables us to work with classes just like how we would work with a OOP supported language model.
  • 31.
    What is aprototype? A prototype is a characteristic that every object in javascript has. Tells us a very specific characteristic about that object Every prototype has information about their parent prototype. It reveals the parent of an object All objects except object literals Date, Array etc has a prototype At the very top of this chain is the object Prototype which has object properties
  • 32.
  • 33.
  • 34.
    Data Structures -The Set Algorithms solve various problems in different running times Algorithms differ in their efficiency with resource usage The Set → stores unique values Advantageous in storing no duplicates. .add() .has() etc
  • 35.
    Data Structures -The Map The Map → has keys and values like objects Difference? → Beat objects with superior keys and size property.
  • 36.
    Demo - DataStrucutres
  • 37.
  • 38.
    Closures Important concept inJS Remember their creation environment and can reference independent variables within that environment. → uses lexical scoping Lexical scoping → refers to the idea that JS and our program keeps track of the location of a variable to understand where it can be accessed. Enable function factories Enable private data
  • 39.
  • 40.
  • 41.
    Generators Breaks the typicalrun to complete model in functions Generators can pause, and resume functions with yield and next() Construct controlled flow functions with simplified iterators. function* is the syntax
  • 42.
  • 43.
  • 44.
    Synchronous vs Asynchronous Synchronousprogramming run in sequence without blocking Asynchronous diverts blocking to event handlers Promises handle Async in ES6 Promises exist in 3 states → Pending, Fulfilled and Rejected
  • 45.
  • 46.
  • 47.
    What’s changed? Not muchwas added from ES6 ES6 was the major upgrade Additional Minor functionality was included 2**5 → Math.pow(2,5); Async Functions → still a proposal
  • 48.
  • 49.

Editor's Notes

  • #4 What I teach today will not be applicable tomorrow as JS is a wildly changing language.
  • #9 Quick Tip → For Linux and mac users introduce nvm. How to init npm Install dependencies Introduce to package.json Run a hello world js file on noded
  • #12 Go to https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&code= And demo it’s play ground. Show scope variable
  • #13 Npm install --save-dev webpack Webpack.config.js → webpack config file const path = require('path'); module.exports = { entry: ['./app/index.js'], output: { path: path.resolve('./dist'), filename: 'bundle.js' } } Npm install babel-core babel-loader webpack-dev-server babel-preset-es2015 babel-polyfill --save-dev What is polyfill → https://www.google.lk/search?q=what+is+polyfill&oq=what+is+polyfill&aqs=chrome..69i57j69i60.3233j0j1&sourceid=chrome&ie=UTF-8 module: { loaders: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/ } ] }, devServer: { port: 3000, contentBase: './dist', inline: true } Package.json "scripts": { "build": "webpack", "start": "webpack-dev-server" }, "babel": { "presets": [ "es2015" ] },
  • #16 Limit = 100; Const limit Let limit Console log it and demonstrate Const emails = [“abc@abc.com”, “aa@a.com”] Const emails = [‘hello@hello.com“] → ERROR! But, emails.push(‘hello@hello.com“); → WORKS! ASSIGNMENT ONLY
  • #18 Let vs const in a block scope { }
  • #21 Template literals first Then, let a = [2, 3, 4]; let b = [1, ...a, 5]; console.log(b); function collect(...a) { console.log(a); } collect("Hi","My","Name","Is","Nilesh"); Let z= [0,1,2,3]; Let [first,second] = z; console.log(first,second); Let student = {id:”it14001821”, name:”nilesh Jayanandana”}; Let {id,name} = student; console.log(id,name); Let student = {id:”it14001821”, name:”nilesh Jayanandana”}; Let id,name; {id,name} = student; → ERROR! ({id,name} = student);
  • #24 This keyword
  • #25 Array.map array.filter((data)=>return data>15); String helpers Let a = `wooh${‘ooo’.repeat(50)}` Let a = “butterfly”.startsWith(‘butter’); .endsWith .includes Number helpers Number.isFinite() → add to cart method Number.isSafeInteger() → Math.pow(2,54) → unsafe;
  • #26 Export a couple of functions and and variables and arrays from a separate js file and import them to index file Export default <module name> → exports a fallback variable for the entire module You can import this by import module_name from ‘./path’ → as opposed to import {module_name} from ‘./path’;
  • #29 class Animal { constructor(name, height) { this.name = name; this.height = height; } hello() { console.log(`Hi my name is ${this.name} from Sri Lanka`); } } let king = new Animal("Nilesh", 5.3); class Lion extends Animal { constructor(name, height, color) { super(name, height); this.color = color; } hello() { console.log(`Hi my name is ${this.name} from Lion Class`); } } // Static methods Class calculator{ Static add(a,b){ Return a*b; } } calculator.add(1,2);
  • #33 function Wizard(name, house, pet) { this.name = name; this.house = house; this.pet = pet; this.greeting = () => `Hello my name is ${this.name} from ${this.house}`; } // add more characteristics and functions Wizard.prototype.pet_name; Wizard.prototype.pet_info = function () { console.log(`pet is ${this.pet} of ${this, pet_name}`); } let harry = new Wizard("Harry", "Griffindor", "Owl"); harry.pet_name = "Hedwig"; console.log(harry.pet_info());
  • #37 SET let a = new Set(); a.add(1); a.add("23"); a.add(23); a.add(23); a.add({ name: 'nilesh' }); a.add([1,2,3,23]); console.log(a); console.log(a.has(10)); Let b = new Set([1,2,3,4,4,4,4,5]); // iterate values For (let element of a.values()){ // code here } Let chars = “asdasdaskjdbasdbnasldsadabksdjand”; Let c = new Set(chars.split()); MAP Let a = new Map(); a.add(‘full name’, ‘Nilesh Jayanandana’); a.add(function,’hellooo’); a.add({},’LOL’); // initializing Let numArr = [[key,val], [key,val]]; // iterating maps for(let [key,value] of numArr.entries()){ // logic } Let string = “assxcghdbcudsjncmeodwkmxuwhbceuhiwjnxmeiw”; Let letters = new Map(); For (let i = 0; i < string.length; i++){ Let letter = string[i]; if(!letters.have(letter)){ letters.set(letter,1); }else{ letters.set(letter,letters.get(letter)+1); } }
  • #40 let call = () => { let secret = "ES6 Rocks"; let reveal = () => { console.log(secret); } return reveal; } let unveil = call(); unveil(); Notice that secret doesn’t get undefined after the function call finishes as it usually should in another programming language. It instead keeps a reference of the values and enables it to be used later on. Factory const addSuffix = (x) => { let concat = (y) => { return y + x; } return concat; } let a = addSuffix("ness"); a("happi"); Private functions const addSuffix = (x) => { let concat = (y) => { return y + x; } return { concat:concat } }
  • #43 function* letterMaker(){ yield 'a'; yield 'b'; yield 'c'; } // no new keyword let a = letterMaker(); console.log(a.next().value()); Function* countMaker(){ Let count = 0; While (count<3){ Yield count = count+1; } } Function* evens(){ Let count = 0; While (true){ count+=2; // can get params from next function Let reset = Yield count; if(Reset){ Count = 0; } } } Let sequel = evens(); console.log(sequel.next().value); console.log(sequel.next().value); console.log(sequel.next(true).value); console.log(sequel.next().value); Iterators vs Generators const arrayIterator = (array) => { let index = 0; return { next: () => { if (index < array.length) { let next = array[index]; index++; return next; } } } } let it = arrayIterator([1, 2, 3, 4]); console.log(it.next()); console.log(it.next()); console.log(it.next()); function* arrayIteratoGen() { // yield arguments; // array // for (let arg of arguments){ // yield arg; // } // iterate and yield easily yield* arguments; } let it = arrayIteratoGen(1, 2, 3); console.log(it.next().value); console.log(it.next().value); console.log(it.next().value);
  • #46 let promise = new Promise((resolve, reject) => { setTimeout(()=>{ resolve('Resolve promise data'); },3000); }); promise.then().catch(); Demonstrate reject and resolve both fetch(url,{method:’GET’}) .then((response)=> response.json()) //chaining promises. Console log request result and show first .then((json)=> console.log(json));