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 (...) : The rest parameter in JavaScript (introduced in ES6) allows a function to accept multiple arguments and collect them into a single array.

Syntax

function functionName(...args) {
// args is an array
}
function sum(...numbers) {
console.log(numbers);
}

sum(1, 2, 3, 4);

Output: [1, 2, 3, 4]

Rest parameter must be the last parameter in a function.

function test(...numbers, a) {
}

Invalid



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

The spread operator (...) in JavaScript (introduced in ES6) lets you expand elements of an array, object properties, or iterable values into individual elements.

1. Spread with Arrays

Used to copy or combine arrays.

const arr1 = [1, 2, 3];

// Copy array
const arr2 = [...arr1];

console.log(arr2); // [1, 2, 3]

Combine arrays:

const a = [1, 2];
const b = [3, 4];

const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4]

2. Spread with Objects

Used to copy or merge objects.

const user = {
name: "Lokman",
age: 25
};

const copy = {...user};
console.log(copy);

Merge objects:

const obj1 = {name: "Lokman"};
const obj2 = {age: 25};

const merged = {...obj1, ...obj2};

console.log(merged);
// {name: "Lokman", age: 25}
Spread does not modify the original array/object (it creates a shallow copy).

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);

});

Syntax: arrays.forEach(callback)

You are passing a callback function.

break only works inside actual loops.

map():

map() is meant to transform an array and return a new array.

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.

const result = [1,2,3].map(function(cur){

    if(cur === 2){
return 100;
}

return cur;
});

console.log(result);

Output: [1,100,3]

return only returns for that one callback execution, not the whole iteration.

//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.

filter():

filter()keep only elements that match a condition.

const nums = [1,2,3,4];

const result = nums.filter(function(cur){
return cur > 2;
});

console.log(result);

output:[3,4]

It creates a new array containing only the elements that passed the condition.

find(): 

find() → returns first matching element only (single value)

const nums = [1,2,3,4,5];

const result = nums.find(function(cur){
return cur > 2;
});

console.log(result);

Output: 3

It stops when first match is found.


Saturday, November 27, 2021

Destructuring in javascript

 Destructuring:  a way to unpack values from arrays or objects into separate variables.

lets see an example,

//ES5

var data = ['lokman',1989];

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

without destructure,

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 .

Rename Variables

const user = {
name: "Lokman",
age: 25
};

const { name: userName, age: userAge } = user;

console.log(userName); // Lokman
console.log(userAge); // 25


Function Parameter Destructuring

const user = {
name: "Lokman",
age: 25
};

function printUser({ name, age }) {
console.log(name, age);
}

printUser(user);



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);

output[31, 21, 11, 1]

//ES6

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

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

console.log(ages);

output[3121111]

//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);

map decides which one is value and which one is index

Implicit return (no {})

JavaScript automatically returns the expression.

const add = (a,b) => a + b;

Same as:

const add = function(a,b){
return a + b;
}
Explicit return (with {})

If you use {}, you must write return.

const add = (a,b) => {
return a + b;
}

If you forget:

const add = (a,b) => {
a + b;
}
console.log(add(2,3)); // undefined
this behavior:
Arrow functions do NOT create their own this.
const person = {
name: "Lokman",
  greet: function(){
console.log(this.name);
}
}

this → points to person

const person = {
name: "Lokman",

greet: () => {
console.log(this.name);
}
}

Output:undefined

Arrow function takes this from outer scope, not from the object.

Example where arrow helps:

const person = {
name: "Lokman",

greet() {
setTimeout(() => {
console.log(this.name);
}, 1000);
}
};
person.greet();

Output:Lokman

 Returning objects

const createUser = () => { name: "Lokman" };

JavaScript thinks {} is a function body.

Result: undefined 

Correct way:

const createUser = () => ({ name: "Lokman" });

Wrap object in ().

Arrow functions are NOT for methods or constructors


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");

}

driverLisence(true);

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

output: lokman born in 1990 have successfully passed the license test

//ES6

function driverLisence(passedTest){

    if(passedTest){

        let name="muna";

        const yearOfBirth=1995;       

    }

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

 }

driverLisence(true);

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

output: ReferenceError: name is not defined

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-




Javascript module

JavaScript Modules (ES6) let you split code into multiple files and reuse code cleanly. Main keywords: export → make something available...