Closures & Callback in JavaScript

Closures:-

One of the greatest features in javascript is closures and it’s widely used but a little bit confusing term of javascript. So let’s understand what is closures. In simple words closures function are gives you access to an outer function from the inner function.

We will start the fundamental term lexical scope known as static scoping. Lexical scoping means is determined by the position of the variable which is declared in our nested scopes or function. Let’s see an example.

For Example:-

const globalVar= 0;




function closuerFunc() {

  const myFirstVar = 1;

  console.log(globalVar); // logs "0"

  function innerOfFunc() {

    const myInnerVar = 2;

    console.log(myFirstVar , globalVar); // logs "1 0"

    function innerOfInnerOfFunc() {

      console.log(myInnerVar, myFirstVar , globalVar); // logs "2 1 0"

    }

    innerOfInnerOfFunc();

  }

  innerOfFunc();

}

closuerFunc();

We can easily understand how to work lexical scope in our closures. But we talk about the closure function let’s see.

function outerClosureFunc() {

  let outerVar = 'I am outside!';

  function innerClosureFunc() {

    console.log(outerVar); // => logs "I am outside!"

  }

  innerClosureFunc();

}

outerClosureFunc();

In other words, here is innerClosureFunc is a Closure because over the variable outerClosureFunc from its lexical scope.

Callback:-

What is a callback?

A callback is just a function that takes some time to give our results and generally async terms(async short for asynchronous) are used for accessing the value from our server. And callback concept is a great example of handling asynchronous behavior in javascript. Let’s see an example.

const secondFunc =()=>{

   console.log('Hello World!');

}




const firstFunc =()=>{

   console.log('I am calling...');

secondFunc ();

}

firstFunc();

Output is

“I am calling…

Hello World”

Leave a Reply