DEV Community

Jacob Stern
Jacob Stern

Posted on

Day 66 / 100 Days of Code: Understanding JavaScript Callbacks

Wed, September 4, 2024

Hey everyone! 👋

How Functions Work in JavaScript Compared to C/C++

In JavaScript, functions are first-class citizens. This means that functions can be passed as parameters to other functions and can also be returned from other functions. When a function takes another function as a parameter or returns a function, it is called a higher-order function, and the function being passed or returned is known as a callback function.

// note: param is a temporary name for the callback function
const higherOrderFunction = param => { 
  param(); 
  return `I just invoked ${param.name} as a callback function!`;
};

const callbackFunction = () => {
  return "I'm being invoked by the higher-order function!";
};

higherOrderFunction(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

This concept is a key element of functional programming, which contrasts with imperative programming. In imperative programming, function state changes and side effects are common. However, in functional programming, functions are designed to be immutable, meaning they do not change state. Instead, new objects are created, and old ones are discarded by JavaScript’s garbage collection.

One significant advantage of functional programming is responsiveness. By making functions immutable, callback functions can complete asynchronously, allowing for near real-time processing.

Another benefit is modularity. Functions can be composed and reassembled, promoting the principle of writing code once and reuse.

There's a lot more to learn, so forging ahead!

Top comments (0)