JavaScript L-3

Block Scope.

"let" and "const" are BLOCK scoped.

"var" is FUNCTION scope.

{
   let firstName="ABC";
   console.log(firstName);
}
//here let can only be inside that block 
//if i write print statement outside block and not inside block then it will not print it.
//similarly goes for const.

Function Scope.

function myApp(){
    if(true){
        var firstN="Abc"
        console.log(firstN);
    }
    console.log(firstN);
}

myApp();
console.log(firstN)

// var can be accessed anywhere outside the block or inside.

Default Parameter.

Default function parameters allow named parameters to be initialized with default values. If no value or undefined is passed.

In JavaScript, the default value of function parameters is undefined, which means if we are not passing any value or arguments into the function parameter, its parameters will have the default value of undefined. However, it’s often useful to set a different default value.

function addTwo(a,b=0){
    return a+b;
}
const ans= addTwo(3);
console.log(ans);
//here b has default value which is equal to 0. So if any value is not passed for b then it will consider b=0.

Rest Parameter.

Basically, in the rest parameter, we can pass any number of arguments.

It represents the extra arguments passed in the function.

It is always prefixed with three dots.

An article with more depth about it(Simplifying Rest Parameters in JavaScript (telerik.com))

function myFunc(a,b,...c){
    console.log(`a is ${a}`);
    console.log(`b is ${b}`);
    console.log(`c is ${c}`,c);
}

myFunc(3,4,4,45,6,2,1);

//here "...c" means all the extra arguments are stored in c as an array.
//so all extra parameter are also accepted here.
//array numbers is created here and any number of arguments can be stored here.
function addAll(...numbers){
    total=0;
    for(let number of numbers){
        total=total+number;
    }
    return total;
}
const answer=addAll(4,4,2);
console.log(answer);

Parameter Destructuring.

This is used for objects.

//directly adding a parameter to access elements of the object.
//destructuring is accessing the properties of the object.
function printDetails({firstName,gender}){
    console.log(firstName);
    console.log(gender);
}
printDetails(person);

CallBack Functions.

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time.

function myFunc(a){    
    a();
}


function myfunc2(){
    console.log("Inside func1");
}

myFunc(myfunc2);

//here myfunc2 is passed as argument under myFunc and calledbcak later.

Function returning Function.

function myFunc(){
    function hello(){
        console.log("hello");
    }
    return hello;
}


const ans=myFunc();
console.log(ans);
ans();
//here function myFunc returns hello function.