Skip to main content

Command Palette

Search for a command to run...

Callbacks in JavaScript and how they work.

Published
2 min readView as Markdown
Callbacks in JavaScript and how they work.

In JavaScript, a callback is a function that is passed as an argument to another function and is executed after that function has finished its task. Callbacks are commonly used in asynchronous programming, where a function needs to perform an operation that may take some time, such as fetching data from a server, and needs to notify the calling code when it is done.

Callbacks are often used with event listeners in web development, where a function is executed in response to a user action, such as clicking a button or scrolling a page. For example, you might have a function that adds an event listener to a button and passes a callback function to be executed when the button is clicked:

javascriptCopy codefunction handleClick() {
  console.log('Button clicked!');
}

const button = document.querySelector('button');
button.addEventListener('click', handleClick);

In this example, handleClick is the callback function that is executed when the button is clicked. The addEventListener method takes the type of event to listen for ('click') and the function to be executed as the callback.

Callbacks can also be used with asynchronous functions, such as the setTimeout function, which waits for a specified amount of time before executing a callback function. Here's an example:

javascriptCopy codefunction delayedLog() {
  console.log('This message will appear after 1 second');
}

setTimeout(delayedLog, 1000);

In this example, delayedLog is the callback function that is executed after a delay of 1000 milliseconds (1 second).

One important thing to note about callbacks is that they can create complex nested code structures, known as callback hell. This can happen when you have several asynchronous functions that depend on each other, and you end up with deeply nested callback functions that can be difficult to read and maintain. To avoid callback hell, you can use promises or async/await syntax, which provide cleaner ways of handling asynchronous code.

In conclusion, callbacks are an important feature of JavaScript that allow you to execute functions after another function has finished its task. They are commonly used in asynchronous programming and event handling in web development. However, it's important to be aware of callback hell and to use alternative solutions such as promises or async/await syntax when working with complex asynchronous code.