SlideShare a Scribd company logo
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

More Related Content

What's hot

Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2
Yeqi He
 

What's hot (20)

ES6 in Real Life
ES6 in Real LifeES6 in Real Life
ES6 in Real Life
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing EraECMAScript 6: A Better JavaScript for the Ambient Computing Era
ECMAScript 6: A Better JavaScript for the Ambient Computing Era
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
JavaScript ES6
JavaScript ES6JavaScript ES6
JavaScript ES6
 
EcmaScript 6
EcmaScript 6 EcmaScript 6
EcmaScript 6
 
Proxies are Awesome!
Proxies are Awesome!Proxies are Awesome!
Proxies are Awesome!
 
ES6: Features + Rails
ES6: Features + RailsES6: Features + Rails
ES6: Features + Rails
 
Async Frontiers
Async FrontiersAsync Frontiers
Async Frontiers
 
Alfresco the clojure way
Alfresco the clojure wayAlfresco the clojure way
Alfresco the clojure way
 
Oral presentation v2
Oral presentation v2Oral presentation v2
Oral presentation v2
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 

Similar to Introduction to Ecmascript - ES6

Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
Matteo Baglini
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.ppt
MENACE4
 

Similar to Introduction to Ecmascript - ES6 (20)

Clojure for Java developers
Clojure for Java developersClojure for Java developers
Clojure for Java developers
 
JavaBasicsCore1.ppt
JavaBasicsCore1.pptJavaBasicsCore1.ppt
JavaBasicsCore1.ppt
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Modern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscanaModern JavaScript Development @ DotNetToscana
Modern JavaScript Development @ DotNetToscana
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !Intro to ES6 and why should you bother !
Intro to ES6 and why should you bother !
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Java scriptforjavadev part2a
Java scriptforjavadev part2aJava scriptforjavadev part2a
Java scriptforjavadev part2a
 
Introduction to es6
Introduction to es6Introduction to es6
Introduction to es6
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Modular programming Using Object in Scala
Modular programming Using Object in ScalaModular programming Using Object in Scala
Modular programming Using Object in Scala
 
Topic2JavaBasics.ppt
Topic2JavaBasics.pptTopic2JavaBasics.ppt
Topic2JavaBasics.ppt
 
hallleuah_java.ppt
hallleuah_java.ppthallleuah_java.ppt
hallleuah_java.ppt
 
2.ppt
2.ppt2.ppt
2.ppt
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 

Recently uploaded

Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Peter Udo Diehl
 

Recently uploaded (20)

WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
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...
 
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...
 
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
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
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
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
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...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 

Introduction to Ecmascript - ES6

  • 1. Introduction to ES6 By Nilesh Jayanandana
  • 3. Welcome to the JS World!
  • 4. 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.
  • 5. Lets setup our Environment Softwares You need, NodeJS → Node and NPM latest versions Visual Studio Code → My favourite Editor
  • 6. 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.
  • 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. Demo → NodeJS and NPM
  • 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
  • 12. Demo - Setting Up webpack
  • 14. 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.
  • 16. 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
  • 18. 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
  • 19. Operating and Destructuring Assignment Spread Operator : { … } Rest Parameter : function( … ){ } Destructuring Arrays and Objects
  • 20. Demo
  • 22. 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
  • 23. Demo - Arrow Functions
  • 24. Demo - Helper Methods
  • 26. Lecture 4 Classes and Prototypes
  • 27. 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
  • 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 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.
  • 31. 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
  • 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 - Data Strucutres
  • 38. 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
  • 39. Demo
  • 41. 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
  • 42. Demo
  • 44. 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
  • 45. Demo
  • 47. 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
  • 49. Q & A

Editor's Notes

  1. What I teach today will not be applicable tomorrow as JS is a wildly changing language.
  2. 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
  3. 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
  4. 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" ] },
  5. 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
  6. Let vs const in a block scope { }
  7. 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);
  8. This keyword
  9. 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;
  10. 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’;
  11. 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);
  12. 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());
  13. 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); } }
  14. 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 } }
  15. 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);
  16. 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));