Ecmascript 6

Variables

different between let and var

{
    var a=12;
    let b=22;
}
console.log(a);//12
console.log(b);// undefined

const

const x = 10
x = 12 // will result in an error!!

const a={};
a.m=12;
console.log(a);//{ m: 12 }
a={};//error

const arr=[1,2,3];
arr.push(4);//[1,2,3,4]
arr=[];//error

var and hoisting

Variable hoisting allows the use of a variable in a JavaScript program, even before it is declared. Such variables will be initialized to undefined by default. JavaScript runtime will scan for variable declarations and put them to the top of the function or script. Variables declared with var keyword get hoisted to the top.

//hoisted to top ; var i = undefined
for (var i = 1;i <= 5;i++){
   console.log(i);
}
console.log("after the loop i value is "+i);
//variable company is hoisted to top , var company = undefined
console.log(company); // using variable before declaring
var company = "TutorialsPoint"; // declare and initialized here
console.log(company);
   var balance = 5000
   console.log(typeof balance)//Number
   var balance = {message:"hello"}
   console.log(typeof balance)//Object

Operators

let a=null;
let b=a||12;//right hand if left hand is false b=12

let a=null;
let b=a&&12;//right hand if left hand is not false

?. and Nullish (??) operator

let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";//right hand if left is null or undefined
console.log(m);//mohammed

Spread operator

<script>
   function addThreeNumbers(a,b,c){
      return a+b+c;
   }
   const arr = [10,20,30]
   console.log('sum is :',addThreeNumbers(...arr))
   console.log('sum is ',addThreeNumbers(...[1,2,3]))
</script>
   //copy array using spread operator
   let source_arr = [10,20,30]
   let dest_arr = [...source_arr]
   console.log(dest_arr)
	
   //concatenate two arrays
   let arr1 = [10,20,30]
   let arr2 =[40,50,60]
   let arr3 = [...arr1,...arr2]
   console.log(arr3)
<script>
   //copy object
   let student1 ={firstName:'Mohtashim',company:'TutorialsPoint'}
   let student2 ={...student1}
   console.log(student2)
   //concatenate objects
   let student3 = {lastName:'Mohammad'}
   let student4 = {...student1,...student3}
   console.log(student4)
</script>

Loops

in loop

let a={a:"hello",b:"world"}
for(let m in a){
    console.log(a[m]);
}

of loop

let a=[1,2,3,4];
for(let m of a){
    console.log(m);
}

label with break

outerloop: // This is the label name
for (var i = 0; i < 5; i++) {
   console.log("Outerloop: " + i);
   innerloop:
   for (var j = 0; j < 5; j++){
      if (j > 3 ) break ; // Quit the innermost loop
      if (i == 2) break innerloop; // Do the same thing
      if (i == 4) break outerloop; // Quit the outer loop
      console.log("Innerloop: " + j);
   }
}

Functions

constructor function

function A(val){
    this.b=val;
}

let a=new A(12);
console.log(a.b);//12
console.log(a instanceof A);//true
console.log(A.prototype===a.__proto__);//true
A.prototype.x=32;
console.log(a.x);//32
console.log(a.hasOwnProperty("x"));//false
a.x=321;
console.log(a.hasOwnProperty("x"));//true
function B(){

}

function A(val){
    this.val=val;
}
A.prototype=new B();
A.prototype.val2=44;

let m=new A(12);
console.log(m instanceof A,m instanceof B);//true true
console.log(m.constructor);//B

Rest parameters

function fun1(...params) { 
   console.log(params.length); 
}  
fun1();  
fun1(5); 
fun1(5, 6, 7); 

Lambda functions

var msg = ()=> { 
   console.log("function invoked") 
} 
msg() 

var msg = x=> { 
   console.log(x) 
} 
msg(10)

Function Hoisting

Like variables, functions can also be hoisted. Unlike variables, function declarations when hoisted, hoists the function definition rather than just hoisting the function’s name.

hoist_function();  //call function
function hoist_function() { 
   console.log("foo"); 
} 
hoist_function(); // TypeError: hoist_function() is not a function  
var hoist_function() = function() { 
   console.log("bar"); 
};

Generator function

"use strict" 
function* rainbow() { 
   // the asterisk marks this as a generator 
   yield 'red'; 
   yield 'orange'; 
   yield 'yellow'; 
   yield 'green'; 
   yield 'blue'; 
   yield 'indigo'; 
   yield 'violet'; 
} 
for(let color of rainbow()) { 
   console.log(color); 
} 
function* ask() { 
   const name = yield "What is your name?"; 
   const sport = yield "What is your favorite sport?"; 
   return `${name}'s favorite sport is ${sport}`; 
}  
const it = ask(); 
console.log(it.next()); 
console.log(it.next('Ethan'));  
console.log(it.next('Cricket')); 

destructing parameters

fun1({A:"hello",B:"world"});
fun2(["hello","world"]);
function fun1({A,B}){
    console.log(A,B);
}
function fun2([A,B]){
    console.log(A,B);
}

bind and apply

function  f(){
    console.log(this.v);
    console.log(arguments);
}
let ob={v:12};
f.bind(ob)();//12
f.apply(ob,["a","b","c"]);//12   [Arguments] { '0': 'a', '1': 'b', '2': 'c' }

Objects

let A={};
let B=A;
let C={};
C[A]=12;
console.log(C[B]);
let k=12;
let A={k};
console.log(A["k"]);
var myCar = new Object(); 
myCar.make = "Ford"; //define an object 
myCar.model = "Mustang"; 
myCar.year = 1987;  

console.log(myCar["make"]) //access the object property 
console.log(myCar["model"]) 
console.log(myCar["year"])

let A={"v1":12};
let B=Object.create(A);
console.log(B.v1);//12
console.log(B===A);//false

delete property

// Creates a new object, myobj, with two properties, a and b. 
var myobj = new Object; 
myobj.a = 5; 
myobj.b = 12; 

// Removes the ‘a’ property 
delete myobj.a; 
console.log ("a" in myobj) // yields "false"

comparing

var val1 = {name: "Tom"}; 
var val2 = {name: "Tom"}; 
console.log(val1 == val2)  // return false 
console.log(val1 === val2)  // return false

object de-structing

<script>
let student = {
   rollno:20,
   name:'Prijin',
   cgpa:7.2
}

//destructuring to same property name
   let {name,cgpa} = student
   console.log(name)
   console.log(cgpa)

//destructuring to different name
   let {name:student_name,cgpa:student_cgpa}=student
   console.log(student_cgpa)
   console.log("student_name",student_name)
</script>
let customers= {
    c1:101,
    c2:102,
    c3:103
}

let {c1,...others} = customers
console.log(c1)//c1
console.log(others)//c2,c3

let emp = {
    id:101,
    address:{
        city:'Mumbai',
        pin:1234
    }
}
let {address} = emp;

console.log(address)
let {address:{city,pin}} = emp
console.log(city)//mumbai

define property

let B={a:1,b:2,c:3};
Object.defineProperty(B,"h",{ enumerable:true, value:4, configurable:true,writable:true});
for(let m in B){
    console.log(m);//a,b,c,h all of them they are enumerable
}
B.h={A:32};//can write on value because it writable
delete  B.h;//can delete because it configurable
console.log(B.h);

set and get

let B={a:1,b:2,c:3};

Object.defineProperty(B,"d",{ set(v) {console.log("hello");
    },get() {console.log("world");
    }});
B.d=345;//hello
let m=B.d;//world

let C={set name(v) {console.log("set ",v);
    },get name() {
    console.log("get");
    }};
C.name=43;//set   43

function constructor(){
    this.val=12;
}
let obj=new constructor();
obj.a=1;
obj.b=2;
console.log(Object.keys(obj));//[val,a,b]

?. and ?? operator

let m=undefined;
console.log(m?.hello)//undefined
let m=undefined??"mohammed";
console.log(m);//mohammed

Number

var num = new Number(10);
console.log(num.toString());
console.log(num.toString(2));//binary
console.log(num.toString(8));//octal

let val=41.2334
console.log(val.toFixed(1))//41.2
console.log(Number(" 12.453  "));//12.453

let val=Number("hello");
console.log(Number.isNaN(val));//true

let val=new Number(12);//instanceof Number
let val=12;//not instanceof Number

String

const str = "Please locate where 'locate' occurs!";
console.log(str.length);//36
console.log(str.indexOf("locate"));//7
console.log(str.toUpperCase());//PLEASE LOCATE WHERE 'LOCATE' OCCURS!
console.log(str.split(' '));//[ 'Please', 'locate', 'where', "'locate'", 'occurs!' ]
console.log(str.endsWith('!'));//true
console.log(str.substr(7))//locate where 'locate' occurs!

let str2="  I  Like  Frutes  ";
str2=str2.trim();
console.log(str2.replace(/(\s+)/i,','));//I,Like  Frutes
console.log(str2.search(/\w{0,2}\s/i));//0
console.log(str2.match(/(\w+\s*)/gi));//[ 'I  ', 'Like  ', 'Frutes' ]

var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);//Hello World

Array

let arr = ["orange", "mango", "banana", "sugar", "tea"];
let removed = arr.splice(2, 0, "water");//no remove only add
console.log(arr);//orange,mango,water,banana,sugar,tea

removed = arr.splice(3, 1);
console.log("After adding 1: " + arr );//orange,mango,water,sugar,tea
console.log("removed is: " + removed);//banana

var arr = ["orange", "mango", "banana", "sugar", "tea"]; 
console.log("arr.slice( 1, 2) : " + arr.slice( 1, 2) );//mango
console.log("arr.slice( 1, 3) : " + arr.slice( 1, 3) );//mango,banana
var arr = new Array("First","Second","Third"); 
var str = arr.join();console.log("str : " + str );  
var str = arr.join(", "); 
console.log("str : " + str );  

var str = arr.join(" + "); 
console.log("str : " + str );

/*
str : First,Second,Third 
str : First, Second, Third 
str : First + Second + Third 
*/
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
array.sort( compareFunction ); //or with no compare functions for numbers ands string array
push(element)//add to end 
unshift(element)//add to first
shift()//remove first
pop()//remove last 
function isBigEnough(element, index, array) { 
   return (element >= 10); 
} 
var retval = [2, 5, 8, 1, 4].some(isBigEnough); 
console.log("Returned value is : " + retval ); //false

var retval = [12, 5, 8, 1, 4].some(isBigEnough); 
console.log("Returned value is : " + retval );//true

var passed = [12, 5, 8, 130, 44].filter(isBigEnough); 
console.log("Test Value : " + passed );  //12,130,44

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);//Array [2, 8, 18, 32]

const array1 = [1, 2, 3, 4];
const reducer = (previousValue, currentValue) => previousValue + currentValue;
console.log(array1.reduce(reducer));// 1 + 2 + 3 + 4=10
console.log(array1.reduce(reducer, 5));// 5 + 1 + 2 + 3 + 4 =15

Map

let daysMap = new Map();
daysMap.set('1', 'Monday');
daysMap.set('2', 'Tuesday');
daysMap.set('3', 'Wednesday');
console.log(daysMap.size);

let andy = {ename:"Andrel"},
    varun = {ename:"Varun"},
    prijin = {ename:"Prijin"}
let empJobs = new Map([[andy,'Software Architect'],[varun,'Developer']]);
console.log(empJobs)//{{…} => "Software Architect", {…} => "Developer"}
'use strict' 
var roles = new Map([ 
   ['r1', 'User'], 
   ['r2', 'Guest'], 
   ['r3', 'Admin'], 
]);
for(let r of roles.entries()) 
console.log(`${r[0]}: ${r[1]}`);

let m=new Map([["ali",1],["mohammed",2]]);
for(let [k,v] of m.entries()){
    console.log(k,v);
}

Promise

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         }
         else
            reject('NOT_Postive_Number_Passed') 
         })
         return p;
   }

   add_positivenos_async(10, 20)
      .then(successHandler) // if promise resolved
      .catch(errorHandler);// if promise rejected

   add_positivenos_async(-10, -20)
      .then(successHandler) // if promise resolved
      .catch(errorHandler);// if promise rejected

   function errorHandler(err) {
      console.log('Handling error', err)
   }
   function successHandler(result) {
      console.log('Handling success', result)
   }

   console.log('end')
function add_positivenos_async(n1, n2) {
    let p = new Promise(function (resolve, reject) {
        if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
        }
        else
            reject('NOT_Postive_Number_Passed')
    })
    return p;
}

add_positivenos_async(10,20)
    .then(function(result){
        console.log("first result",result)
        return add_positivenos_async(result,result)
    }).then(function(result){
    console.log("second result",result)
    return add_positivenos_async(result,result)
}).then(function(result){
    console.log("third result",result)
})

console.log('end')

promise.all()
This method can be useful for aggregating the results of multiple promises.

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         }
         else
            reject('NOT_Postive_Number_Passed')
      })

      return p;
   }
   //Promise.all(iterable)

Promise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)])
   .then(function(resolveValue){
      console.log(resolveValue[0])
      console.log(resolveValue[1])
      console.log(resolveValue[2])
      console.log('all add operations done')
   })
   .catch(function(err){
      console.log('Error',err)
   })
   console.log('end')

/*
end
30
70
110
all add operations done
*/

promise.race() This function takes an array of promises and returns the first promise that is settled.

   function add_positivenos_async(n1, n2) {
      let p = new Promise(function (resolve, reject) {
         if (n1 >= 0 && n2 >= 0) {
            //do some complex time consuming work
            resolve(n1 + n2)
         } else
            reject('NOT_Postive_Number_Passed')
      })

      return p;
   }

   //Promise.race(iterable)
   Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)])
   .then(function(resolveValue){
      console.log('one of them is done')
      console.log(resolveValue)
   }).catch(function(err){
      console.log("Error",err)
   })

   console.log('end')

async

async function  fun(){
    return 100;
}

Promise.all([fun(),fun(),fun()]).then((res)=>{
    console.log(res);});

await


async function  fun(){
    return 100;
}

async  function  fun2(){
    let prom=Promise.all([fun(),fun(),fun()]);
    let res=await prom;
    return res;
}

fun2().then(res=>{console.log(res)});//[ 100, 100, 100 ]
async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait until the promise resolves (*)

  alert(result); // "done!"
}

f();

class

class A{
    m=12;
    constructor(val) {
        console.log(val);
        this.m=val;
    }
    set value(val){
        this.m=val;
    }

    get value() {
        return this.m;
    }
}

let a=new A(12);//12
a.value=22;
console.log(a.value);//22
class A{
    m=12;
    constructor(val) {
        console.log("A : ",val);
        this.m=val;
    }
    set value(val){
        this.m=val;
    }

    get value() {
        return this.m;
    }
}
class B extends A{
    constructor(val) {
        super(val);
        console.log("B : ",val)
    }
}
let b=new B(12);//A : 12 B : 12
class A{
    #m=12;//private field
}

get constructor from object

class A{
}

let a=new A();
console.log(a.constructor==A);//true

call super members

class A{
    constructor() {
    }
    fun(){
        console.log("A");
    }
}

class B extends A{
    constructor() {
        super();
    }
    fun(){
        super.fun();
        console.log("B");
    }

}

let b=new B();
b.fun();//A B

export and import

// export an array
export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

// export a constant
export const MODULES_BECAME_STANDARD_YEAR = 2015;

// export a class
export class User {
  constructor(name) {
    this.name = name;
  }
}

export function sayHi(user) {
  alert(`Hello, ${user}!`);
}  // no ; at the end

// ? say.js
function sayHi(user) {
  alert(`Hello, ${user}!`);
}
function sayBye(user) {
  alert(`Bye, ${user}!`);
}
export {sayHi, sayBye}; // a list of exported variables

// ? main.js
import {sayHi, sayBye} from './say.js';
sayHi('John'); // Hello, John!
sayBye('John'); // Bye, John!

// ? main.js
import * as say from './say.js';
say.sayHi('John');
say.sayBye('John');
// ? main.js
import {sayHi as hi, sayBye as bye} from './say.js';

hi('John'); // Hello, John!
bye('John'); // Bye, John!
// ? say.js
...
export {sayHi as hi, sayBye as bye};

// ? main.js
import * as say from './say.js';

say.hi('John'); // Hello, John!
say.bye('John'); // Bye, John!

Export default

In practice, there are mainly two kinds of modules.

  1. Modules that contain a library, pack of functions, like say.js above.
  2. Modules that declare a single entity, e.g. a module user.js exports only class User.

Mostly, the second approach is preferred, so that every “thing” resides in its own module.

// ? user.js
export default class User { // just add "default"
  constructor(name) {
    this.name = name;
  }
}

// ? main.js
import User from './user.js'; // not {User}, just User
new User('John');
function sayHi(user) {
  alert(`Hello, ${user}!`);
}

// same as if we added "export default" before the function
export {sayHi as default};

// ? user.js
export default class User {
  constructor(name) {
    this.name = name;
  }
}

export function sayHi(user) {
  alert(`Hello, ${user}!`);
}

// ? main.js
import {default as User, sayHi} from './user.js';

new User('John');

// ? main.js
import * as user from './user.js';

let User = user.default; // the default export
new User('John');

re-export

export {sayHi} from './say.js'; // re-export sayHi
export {default as User} from './user.js'; // re-export default
export * from './user.js'; // to re-export named exports
export {default} from './user.js'; // to re-export the default export

operators

Operator_NameDescriptionExample
inIt is used to check for the existence of a property on an object.let Bike = {make: ‘Honda’, model: ‘CLIQ’, year: 2018}; console.log(‘make’ in Bike); // Output: true
deleteIt is used to delete the properties from the objects.let Bike = { Company1: ‘Honda’, Company2: ‘Hero’, Company3: ‘Royal Enfield’ }; delete Bike.Company1; console.log(Bike); // Output: { Company2: ‘Hero’, Company3: ‘Royal Enfield’ }
typeofIt returns the data type of the operand.let message = “Welcome to ” + “JavaTpoint”; console.log(typeof message); // Output: String
instanceofIt is used to check if the object is of a specified type or not.let arr = [1, 2, 3]; console.log( arr instanceof Array ); // true console.log( arr instanceof String ); // false

Typescript

class A{
}
let m:A;
//============================
type AA={
    m:string
}
let mm:AA={m:"hello"};
//=================================
function fun(l:number,s:boolean):void{//can return null or undefined or nothing
    return undefined;
}

function fun2(cb,a?:string){ //second parameter can be empty
}
fun2(()=>{});
//===============================
let strArr:string[];//accept only array of string
let strArr2:[string,number];//accept only array of strings and numbers
let strArr3:Array<string>;
//========================
let any:any;//take any value

to build js from ts file you can

npm install typescript -D -g
npm link typescript
tsc file.ts