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!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay