This document provides an introduction and overview of ECMAScript 6 (ES6), the latest version of JavaScript. It discusses setting up the development environment with Node.js and npm. Key ES6 features covered include arrow functions, block scoping, template literals, destructuring, classes, modules, and promises. The document consists of 9 lectures with demonstrations of these new JavaScript features. It aims to help readers learn the major updates and capabilities introduced in ES6.
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
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
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
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
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.
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
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
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
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
What I teach today will not be applicable tomorrow as JS is a wildly changing language.
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
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
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
Let vs const in a block scope
{
}
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);
This keyword
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;
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’;
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);
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());
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);
}
}
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
}
}
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);
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));