Closures and callbacks in Javascript

charliekroon

charliekroon

Posted on April 24, 2023

Closures and callbacks in Javascript

In the month of April, I'll publish a small blog series called "Questions from the Past". I'll be going through my old notebooks from my first year as a developer and answering the questions I think are most important. Today we will go into Closures and Callbacks in Javascript.

Closures
Closures are functions that have access to variables from an outer function, even after the outer function has finished executing. This might sound a bit confusing, but let's go through it together.
Imagine you have a function that defines a variable, like this:

function outerFunction() {
  let outerVariable = "Hiiii!";

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const inner = outerFunction();
inner(); // logs "Hiiii!" to the console
Enter fullscreen mode Exit fullscreen mode

In this example, innerFunction has access to outerVariable, even though it's not defined inside the innerFunction itself. This is because innerFunction closes over outerVariable, creating a closure that allows it to access the variable's value even after outerFunction has finished executing.

Callbacks
A callback is a function that is passed as an argument to another function and is executed at a later time. Here's an example:

function doSomething(num1, num2, callback) {
  let result = num1 + num2;
  callback(result);
}

function logResult(result) {
  console.log(`The result is ${result}`);
}

doSomething(3, 4, logResult); // logs "The result is 7" to the console
Enter fullscreen mode Exit fullscreen mode

In this example, logResult is a callback function that's passed as an argument to doSomething. When doSomething is executed, it performs an operation on num1 and num2 and then calls the callback function, passing in the result as an argument. In this case, logResult is executed and the result is logged to the console.

That's all there is to it! Once you get a handle on closures and callbacks, you'll be able to write better and more efficient code.

💖 💪 🙅 🚩
charliekroon
charliekroon

Posted on April 24, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related