Follow us

Modern JavaSccript / ES6 / ECMAScript.

Hi Viewers,

I thout lets put some of my effert on learning "client side development" and the first step I belive you must be aware of modern javascript concepts.

I have created this article and tried putting all the basic and useful concepts of modern javascript / es6 / ECMA script and I am sure this is something either you are working with Angular, React or any other client side development you must need the concepts of modern javascript.

For below examples, I created react app and then work with Index.js file(Make sure node is installed on your machine)-
Command to create react app on cmd : npx create-react-app myfirstreact
Then use command to open project with vs code : code .
Do your changes and to run, use "yarn start" command on terminal and it will give you localhost url.

 

console.log("*******************Variable declaration and scope******************");

/*

Keep remember, when you declare variable, you have to assign default value as 

type of variable get decided as per value assigned.

let : block scope only.

const : block scope only and one time value assignment and cannot cahnged.

var : block and outside block scope access.

*/

function test(){

  // eslint-disable-next-line

  if(1 === 1){

    let letValue="let value";

    var varValue="var value";

    const constValue="const value";

    

    console.log("Let value : "+ letValue);

    console.log("Var value : "+ varValue);

    console.log("Const value : "+ constValue);

    //constValue="const updated value"; //cannot update the value

  }

  //console.log("Let value access outside : "+ letValue); //cannot access here

  console.log("Var value access outside : "+ varValue);

  //console.log("Const value access outside : "+ constValue); //cannot access here

}

test();

 

console.log("*******************Object declaration, scope and this keyword******************");

/*

this keywork - with standard java script this represent the reference to caller. So in this example when I calling the method like 

Uesr.enroll(); - this will give the reference of user object and you can see the output same in console with name value. 

And when calling the method like "const clone_enrollfun = user.enroll; waclone_enrollfunlk(); - so here "clone_enrollfun" will be undefined 

as this keyword generally if this does not find reference then it give you global object i.e. window, so here to solve this undefined problem, 

refer the below example where you have to "bind" to get the reference copy.

*/

const user = {

  name: "Rajeev"//variable

  email: "rajeev@test.com"//variable

  enroll: function() {

    console.log ("enroll function called, name : " + this.name);

  }, //function

  enrollv2 () {

    console.log ("enroll v2 function called, name : " + this.name);

  } //function alternate way

};

console.log(user);

console.log(user.enroll()); //this will print name as directly using user object reference.

console.log(user.enrollv2()); //this will print name as directly using user object reference.

console.log("Email is : " + user.email);

const clone_enrollfun = user.enroll;

clone_enrollfun(); //here name will not print with funtion call as this represent the caller and in this we have not bind the User object ference.

const clone_enrollfun2 = user.enroll.bind(user);

clone_enrollfun2(); //here name will print as now object reference is bind.

console.log("*******************this keyword with parent child function in object******************");

const liveDateTime = {

  appName: "Test App",

  getDateTime () {

    var thisRef= this//get this assinged into variable, so that it can be accessed in child function

    setTimeout(() => {

      var today = new Date();

      console.log("Curent Date Time For(ref this) "+thisRef.appName+", and for (this) : "+this.appName +" : "

      + (today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate() +" "+today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds()));

    }, 1000000);

  }

}

liveDateTime.getDateTime();

 

console.log("*******************Arrow function******************");

const fun_no_parameter = () => console.log("10+20 = "+(10+20));

const fun_with_one_parameter = (parameter1_name) => console.log("Name value is : "+parameter1_name);

const fun_with_multiple_parameter = (parameter1_num1, parameter1_num2) => console.log("Sum of nu1 and num2 : "+(parameter1_num1 + parameter1_num2));

fun_no_parameter();

fun_with_one_parameter("Rjaeev");

fun_with_multiple_parameter(100200);

 

console.log("*******************List, Filter to apply where condition and loop******************");

/*Filter - to apply where condition with list or array*/

const userList = [

  {id:1, name:"Amit", isActive:true},

  {id:2, name:"Sumit", isActive:false},

  {id:3, name:"Kumit", isActive:true}

]

const activeUsers = userList.filter(u=> u.isActive===true);

console.log(activeUsers);

userList.forEach(u=>

  console.log("Id = "+u.id+", Name = "+u.name)

);

 

console.log("*******************Map - decorate each items of array or list and litral template backtick character(`) usages******************");

/**

 Map - to work each items and mainly used when you want to decorate something with each items of array or list, 

 like in this example I have colors array I want to list as bullets each color. Here I have also used template literal with backtick character.

 */

const decoreatedUserList = userList.map(u=> '<div> User Name <b>'+u.name+'</b>, and Id <b>'+u.id+'</b></div>');

//or use "template litral with backtick character i.e. `(you will find this char just before 1 key)"

const decoreatedUserList2 = userList.map(u=> `<div> User Name <b>${u.name}</b>, and Id <b>${u.id}</b></div>`);

console.log(decoreatedUserList2);

decoreatedUserList2.forEach(u=>

  document.write(u)  

);

 

console.log("*******************Object deconstruction******************");

/*

Destructuring - when you want to deconstruct any object from one to another like in below example I have address object and if want to

take value of each items of address object then I can access like object.item1 i.e. address.street so I can achieve this directly 

assigning objects to other const having same names compare to address object or even if I have different name then I have to do mapping 

like "address-object-item-name: con-item-name".

*/

const userDetail = {

  name : "Amit",

  id : 1,

  addressHome: "Delhi"

}

const {name, id, addressHome:address } = userDetail; /*here object deconstructed into variable so now you can directlry access with name or id 

else you have to access like userDetail.name. Similary if you want to change name while deconstructing then same you can do like in this 

example address variable is happending*/

console.log(`Name is ${name}, id is ${id} and address is ${address}`);

 

console.log("*******************Spread Operator(…) to assign/clone object state to other******************");

/*

Spread Operator(…) - when you have list or array and you want to combine them or combine with some custom values as well or if you want 

to clone the values then you use this operator as three dots …

*/

const userIdentity = {

  name : "Amit",

  id : 1

}

const userProfile={

  email: "test@test.com",

  mobile: 1212121

}

const userFullDetail = {...userIdentity, ...userProfile, address:"Delhi"}//here both object along with one variable getting declared and assigned to userFullDetail object

console.log(userFullDetail);

 

console.log("*******************Class and constructor, inheritance, super()******************");

class UserClass{ //class

  name = "rajeev"//variable

  enroll(){ //class method

    console.log("enroll function of user class called, name is : "+this.name);

  }

}

const obj = new UserClass(); //object creation

obj.enroll(); //function call using object

/**class with constructor */

class UserClassWithConstructor{ //class

  name = "rajeev"//variable

  constructor(_name){

    this.name = _name;

  }

  

  enroll(){ //class method

    console.log("enroll function of user class with constructor called, name is : "+this.name);

  }

}

const obj2 = new UserClassWithConstructor("rajeev update"); //object creation

obj2.enroll(); //function call using object

/**class inheritance */

class UserClassWithConstructor2 extends UserClassWithConstructor{ //class inheritance with extends keywords

  email = "rajeev@test.com"//variable

  constructor(_name, _eamil){

    super(_name); //calling base class constructor

    this.email = _eamil;

  }

  

  enroll(){ //class method

    console.log("enroll function of child user class with inheritance, name is : "+this.name+", and emai is "+this.email);

  }

}

const obj3 = new UserClassWithConstructor2("rajeev update""rajeevupdate@test.com"); //object creation

obj3.enroll(); //function call using object (this will call both parent and child function both, first parent and then child)

 

console.log("*******************Promise, for resolve and reject logic like your API call******************");

/*

Promise, used when you have success and fail scenario like you are doing registration and you have different types

of user and based on type you want to resolve/accept or reject/catch/fail.

Similarly like you are doing any web API call and if you get API 200(OK) and it means resolved or else rejected/catch.

 */

function doUserRegistration(userType){

  /*defining promice with resolve and reject parameter and here name can be anything to the parameter but

  the first prameter will treat as resolve and second parameter will treat as reject behaviour*/

  return new Promise((resolve, reject)=>{

    if(userType==="Admin"){

      resolve({message:"success", code:"ad01"});

    }

    else if(userType==="Support"){

      resolve({message:"success", code:"sp01"});

    }

    else{

      reject("failed");

    }

  });

}

doUserRegistration("Admin").then((respose)=>{

  console.log("Success response : "+respose.message);

}).catch((respose)=>{

  console.log("Fail response : "+respose);

});

doUserRegistration("Callcenter").then((respose)=>{

  console.log("Success response : "+respose.message);

}).catch((respose)=>{

  console.log("Fail response : "+respose);

});

 

 

console.log("*******************Modules, named and default export to use multiple files with different class and functions******************");

/**

 Modules - is just concept when you have separate your class into multiple files and then you make them as export and then you 

 import them where you want to use. So with below example create person class as export and then create Techer class which inherit the 

 person class to imported that one and then into main index  to call the Teacher class again import that and called.

 Named and default exports, so when you import you use brace sign i.e. { you-class-name-here } but with default export you do 

 not require  this braces sign{}. And if you have both like default and named export both then you have to use both like 

 "your-default-classOrFunction { named-classOrFunction }". Name export example where create promote function as export type and 

 same accessible in other file.

 */

/*

 //Created "User_Identity.js" file with below code -

 export class User_Identity_Export_Class{ //class

    constructor(_name, _id){

        this.name=_name; //name variable for class scope level will be declared and used

        this.id=_id; //id variable for class scope level will be declared and used

    }

    

    IdentitySubmit(){ //class method

      console.log("IdentitySubmit function of UserIdentityExport class called, name is : "+this.name+", and id is "+this.id);

    }

}

export default function ExportDefaultFunction(){ //default export function

    console.log("ExportDefaultFunction function SubmitUser called");

}

 

//Code on index.js where imported both class and function and used-

import ExportDefaultFunction, {User_Identity_Export_Class} from "./User_Identity";

console.log("*******************Modules, named and default export******************");

class UserEnrollment extends User_Identity_Export_Class{

  constructor(_name, _id, _address){ 

    super(_name, _id); //exported class base constructor call 

    this.address=_address; //address variable for class scope level will be declared and used

  }

  EnrollUser(){

    console.log("UserEnrollment child class function called, name is : "+this.name+", and id is "+this.id+", address is "+this.address);

  }

}

const userEnrollmentObj = new UserEnrollment("Rajeev", 101, "New Delhi"); //contructor call

userEnrollmentObj.IdentitySubmit(); //callled parent export class method

userEnrollmentObj.EnrollUser(); //callsed child/this class function

ExportDefaultFunction(); //called default export function

 */

Categories/Tags: Modern JavaSccript~ES6~ECMAScript

Recent Articles

1

AWS Saving Plan - Cost optimization tips

2
3

AWS RDS Key Concepts & Why you should use it?

4
5

Open-Search/Kibana - Multi Tenancy Setup

See All Articles