07 - Functions in JS

// Function definition
function sayHello() {
    console.log("Hello Everyone");
}


// // function call
sayHello();

// ----------------------------------------------
function add(x, y) {
    
    let res = x + y;

    console.log(res);
}

add(2, 3);
add("hello", "world");
add("", 10);
add("hello", 10);
add(true, 5);
add([], 15);


// -----------------------------------------------
// default arguments
function substract(a,b,c=2) {
    
    return a - b -c;
}

let ans1 = substract(12, 5,4);
console.log(ans1);
let ans2 = substract(12,5);
console.log(ans2);


// --------------------------------------------

console.log("Start");
function d() {
    console.log("Hello");
}

var b = 100;
function a() {
    d();
    console.log(b);
}
a();


// OUTPUT:
// ======== 

// Hello Everyone
// 5
// helloworld
// 10
// hello10
// 6
// 15
// 3
// 5
// Start
// Hello
// 100

//----------------------------------------------------------------------------

// Higher Order function
function func() {
   
   function innerFun() {
       console.log("Inside Inner Fun")
   }
   
   return innerFun;
}


let xy = func();
console.log('\nDefinition of function xy: ');
console.log(xy);
xy();

// OUTPUT:
// Definition of function xy: 
//  ƒ innerFun() {
//       console.log("Inside Inner Fun")
//   }
// Inside Inner Fun

// -------------------------------------------------------------

console.log(x);

fun();

function fun() {
    console.log("Inside fun")
}

var x = 100;

// OUTPUT:
// undefined
// Inside fun

// -------------------------------------------------

console.log(z);
// Function expression
var z=function a() {
    console.log("Hello");
}

console.log(z);

// OUTPUT:
// undefined
// ƒ a() {
//    console.log("Hello");
// }

//----------------------------------------------------------------------------

// Temporal Dead Zone(TDZ):-
===========================
//Statement(console.log(xx);) in below code will generate reference error: 
    //Uncaught ReferenceError: Cannot access 'xx' before initialization at Line 1XX
//WHY?
//Because the let and const variables exist in the TDZ from 
    //the start of their enclosing scope until they are declared. 

console.log(xx); //xx here exists in TDZ until its declared later.
zz();

function zz() {
    console.log("Inside zz");
}

let xx = 100;

//Note: to read more about TDZ, 
// and also the difference between the let/const and var variables,
//Click here