innovationM
← Back to Blogs

Java Application

Closures & Callback in JavaScript

InnovationM Admin 17 Mar 2022 2 min read
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”

About the Author

InnovationM Admin

Contributor at InnovationM.

LinkedIn

Transform Your Ideas with Expert Guidance

icon
15+ Years of Expertise

Delivering high-impact solutions with years of industry experience.

icon
100+ Satisfied Clients

Helping contact industry software experts to achieve their brand goals.

icon
250+ In-House Team Members

A skilled team ready to tackle projects of any scale.

Book a consultation call with our experts today