Sunday, November 28, 2021

default parameter in javascript

//ES5 

function person(name,age,profession){

    profession===undefined?profession="engineer":profession=profession;

    this.name = name;

    this.age = age;

    this.profession = profession;

}

var lokman = new person('lokman',32);//In javascript no need to provide all the parameter when a function                                                                 is called.

console.log(lokman);

//ES6

function person(name,age,profession='engineer'){

    this.name = name;

    this.age = age;

    this.profession = profession;

}

var lokman = new person('lokman',32);


Rest parameter in javascript

 Rest parameter is opposite of spread operator . In rest parameter function takes an argument list and transform it into an array .

--Spread operator is used in the function call.

--While rest parameter is used in function declaration .

lets see an example,

//ES5

function isFullAge(){

 var args=Array.prototype.slice.call(arguments);   //taking the arguments and converting into an array

  args.forEach(function(cur){

     console.log((2016-cur)>=18);

  });

}

isFullAge(1990,1995,2000);

//ES6

function isFullAge6(...args){ //no need to convert transform into an array .it automatically transformed                                                   using rest parameter.

    args.forEach(cur => console.log((2016-cur)>=18));

}

isFullAge6(1990,1995,2000);




Difference between splice() and slice() in javascript array

slice()- returns a shallow copy of a portion of given array .
ex:
var a=['j','u','r','g','e','n'];
console.log(a.slice(3,5));
output: ["g","e"]

splice() - returns the removed elements from an array . It effects the orginal array .
var a=['j','u','r','g','e','n'];
console.log(a.splice(3,5));
output:["g", "e", "n"]
orginal array:['j','u','r']

Spread operator in javascript

 Spread operator introduced in ES6.The syntax is three dot(...variable name). It expands the array into individual elements.We can use to insert any element into any position in a array .

ex:

const familyLokman=['lokman','muna','tutul'];

const familySohel=['sohel','ruma','imran'];

const familyBig=[...familyLokman,...familySohel];

console.log(familyBig);

here,familyLokman and familySohel is two array .No we want to merge it into one array then we can use spread operator. 

we can use spread operator for dom nodes too.

const h = document.querySelector('h1');//h1 is the dom element with no class name and id .only tag                                                                         name

const boxes=document.querySelector('.boxes');//boxes is the class name which return nodeslist

const all=[h,...boxes];//add all node to all array

Array.from(all).foreach(el=>//Array.from(all) converting node list into an array 

el.style.color='purple');




Arrays in javascript

 N.B- we can iterate an array using foreach and map in javascript like below-

var arrays = [1,2,3,4,5];

//foreach

arrays.forEach(function(cur){

    if(cur===1){

        break; //break and continue is illegal in foreach .

   }    console.log(cur);

});

//map

arrays.map(function(cur){

    if(cur===2){

        break;////break and continue is illegal in map.

    }

    console.log(cur);

});

so the solution is to use regular for loop-

//ES5

for(var i=0;i<arrays.length;i++){

    if(i===3){

        break;

    }

    console.log(arrays[i]);

}

//ES6

const arrays = [7,1,2,3,4,5];

for(const cur of arrays){

    if(cur===3){

        continue;

    }

    console.log(cur);

}

we can use for--of loop to iterate easily over an array in ES6.



Saturday, November 27, 2021

Destructuring practical example.

When we need to return multiple values from  a function we can return a object of having the values .But using destructure we can do this . lets see the example,

function calculateRetirement(year){
    const age = new Date().getFullYear()-year;
    return[age, 65-age];
}

const[age,retirement]=calculateRetirement(1989);
console.log(`age${age} retirement${retirement}`);

Destructuring in javascript

 Destructuring:  Destructuring is the process of extract data from a data structure .

lets see an example,

//ES5

var data = ['lokman',1989];

console.log(`data ${data}`);

var name=data[0];

var yearOfBirth=data[1];

console.log(`name=${name} year of birth=${yearOfBirth}`);

Here, we need two variable to extract data from the 'data' data structure  in es5.

But we can do this by using destructuring in es6.

const [name,yearOfBirth]=['lokman',1989];

console.log(name);

console.log(yearOfBirth);

here ,name and yearOfBirth will be two variable to store data from the array .

We can extra properties from object using destructure. let's do that,

const obj={

    firstName: 'lokman',

    lastName:'hossain'

}

const { firstName,lastName}=obj;

console.log(`first Name:${firstName} last Name:${lastName}`);

N.B:here property name should be same as in object .

What to do if we don't want to match property name as in object .

const {firstName:a,lastName:b}=obj;

console.log(`first name:${a} last name:${lastName}`);

we just define alias of the property name which will be the new const variable.



Thursday, November 25, 2021

More about arrow function --

 The biggest advantages of using arrow function is that they share the surrounding 'this' keyword.

Arrow function do not have their own 'this' keyword. They simply uses the 'this' they written in .

Lets see an example,

var box ={

    color:"green",

    position:1,

    clickMe:function(){ 

       console.log('inside method of box object '+ this.color+' '+this.position);

        document.querySelector(".green").addEventListener('click',function(){

            console.log("inside regular function call of event listener");

            var str='this is a box with color'+this.color+' which position is'+this.position;

            alert(str);

        })

    }    

}

box.clickMe();

We already know that in regular function call 'this' will point to the global object which is window object. But in  method call  'this' will point to the object the method call from .

So, in the above example 'this' will point to the box object ,so the color and position of box property will give the proper output, but in the listener callback method is a regular function call so 'this' will point to the global object(window). so color and position will give undefined as output.

So, a simple solution is we can store 'this' to a variable and can use that. let see-

var box ={

    color:"green",

    position:1,

    clickMe:function(){ 

     var self=this; //this is the hack

       console.log('inside method of box object '+ this.color+' '+this.position);

        document.querySelector(".green").addEventListener('click',function(){

            console.log("inside regular function call of event listener");

            var str='this is a box with color'+self.color+' which position is'+self.position;

            alert(str);

        })

    }    

}

box.clickMe();

Here, we are storing the 'this' of the object so that now we can use it to regular function call to get our desired output.

But we can easily do this by using arrow function in javascript. Because we already know arrow function uses the lexical 'this' keyword.

const box ={

    color:"green",

    position:1,

    clickMe:function(){

       console.log('inside method of box object '+ this.color+' '+this.position);

        document.querySelector(".green").addEventListener('click',()=>{

            console.log("inside regular function call of event listener");

            var str='this is a box with color'+this.color+' which position is'+this.position;

            alert(str);

        })

    }    

}

box.clickMe();







Wednesday, November 24, 2021

What is Arrow function in javascript?

Arrow functions introduced in ES6. It  provides a concise way to write javascript function.

//ES5

const years=[1990,2000,2010,2020];

var ages= years.map(function(el){

   return 2021-el;

});

console.log(ages);

//ES6

const years = [1990,2000,2010,2020];

let ages = years.map(el=>2021-el);//This is called arrow function.

console.log(ages);

//Arrow function with multiple parameter

const years = [1990,2000,2010,2020];

let ages = years.map((el,index)=>`age element ${index+1}:${2021-el}`);

console.log(ages);



Tuesday, November 23, 2021

Data privacy in ES5 and ES6

 To make a variable private we have used IIFE in ES5.

//ES5

(function(){

    var c=10;

})();

console.log(c);// 'c' can't be accessible outside of the IIFE 

But in ES6 we can do this in easier way ,

{

       let a =10;

}

console.log(a);

//variable a cannot be accessed outside of the block .because they are blocked scoped.

Monday, November 22, 2021

Difference between var ,let and const?

 'var' is function scoped but 'let' and 'const' are blocked scoped .

example-

//ES5

function driverLisence(passedTest){

    if(passedTest){

        var name="lokman";

        var yearOfBirth=1990;

    }

      console.log(name+"  born in " +yearOfBirth+"have successfully passed the license test");

//name and yearOfBirth will accessible within the body of the function because var is function scoped.

}

driverLisence(true);

//ES6

function driverLisence(passedTest){

    if(passedTest){

        let name="muna";

        const yearOfBirth=1995;

       

    }

     console.log(name+"  born in " +yearOfBirth+"have successfully passed the license test");

//name and yearOfBirth will not accessible outside of the if block . because they are blocked scoped. 'const' will not changed once initialized.

 }

driverLisence(true);

Wednesday, November 17, 2021

Event delegation?

Event delegation is the process of not to add event to a target element , add the event to the parent element.

Use cases for event delegation-

1. When we have an element with lots of its child element that we are interested in .

2.When we want an event handler attached to an element but not exist in DOM when page is loaded .

what is Event bubbling?

 If any event fired on a DOM element it will also fired on all of its parent element which is called the event bubbling.

So, the element event first fired is called the target element.

Ex:

<main>

     <section>

         <p>

                <button>

                          target  element        //event first fired on button element so it is called the target                                                                        element.

              </button>

         </p>

     </section>

</main>

This target element will store in the event object as property .

Monday, November 8, 2021

Structure of project using module pattern in javascript

 


Module pattern in javascript

Lets have an example -
var controller = (function () {
    var a = 10;  //private variable
    var add = function (a) {  //private function
        return a + 10;
    }

    return {
        publicTest: function (b) { //public method
            console.log(add(b));
        }
    }
})();

Here introducing a module pattern in javascript. 'controller'  is a module . 'a' variable and function 'add' both are inside an IIFE. we already know that an IIFE creates its own execution context .so variable 'a' and function 'add' can't be accessed outside of the the module 'controller'. This is called encapsulation .

Here , IIFE returns an empty object ,by using that object we can call 'publicTest' method.
This is the beauty of module pattern . 

Here,IIFE already return an object ,then how we access the private variable and function inside IIFE.
The answer they both accessed because of closure .

Sunday, November 7, 2021

Project planning in Javascript?

 Steps:

First understand about the requirement of the project .

Write what functionality should have in this project .

Then define modules for individual part .

Then define which functionality should have in which modules.

Then write down code for individual modules.

Ex:




                              Then define  the above requirement to individual modules as like below-




Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...