JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript callbacks.

"I will call back later!"

A callback is a function passed as an argument to another function

This technique allows a function to call another function

A callback function can run after another function has finished

Function Sequence

JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.

This example will end up displaying "Goodbye":

Try it Yourself »

This example will end up displaying "Hello":

Sequence Control

Sometimes you would like to have better control over when to execute a function.

Suppose you want to do a calculation, and then display the result.

You could call a calculator function ( myCalculator ), save the result, and then call another function ( myDisplayer ) to display the result:

Or, you could call a calculator function ( myCalculator ), and let the calculator function call the display function ( myDisplayer ):

The problem with the first example above, is that you have to call two functions to display the result.

The problem with the second example, is that you cannot prevent the calculator function from displaying the result.

Now it is time to bring in a callback.

Advertisement

A callback is a function passed as an argument to another function.

Using a callback, you could call the calculator function ( myCalculator ) with a callback ( myCallback ), and let the calculator function run the callback after the calculation is finished:

It is passed to myCalculator() as an argument .

When you pass a function as an argument, remember not to use parenthesis.

Right: myCalculator(5, 5, myDisplayer);

Wrong: myCalculator(5, 5, myDisplayer()) ;

It is passed to removeNeg() as an argument .

When to Use a Callback?

The examples above are not very exciting.

They are simplified to teach you the callback syntax.

Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like waiting for a file to load).

Asynchronous functions are covered in the next chapter.

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Create a custom callback in JavaScript

All I need to do is to execute a callback function when my current function execution ends.

A consumer for this function should be like this:

How do I implement this?

Wicket's user avatar

  • 3 object.LoadData(success) call must be after function success is defined. Otherwise, you will get an error telling you the function is not defined. –  J. Bruni Commented Dec 29, 2011 at 13:41

11 Answers 11

Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.

That will call doSomething , which will call foo , which will alert "stuff goes here".

Note that it's very important to pass the function reference ( foo ), rather than calling the function and passing its result ( foo() ). In your question, you do it properly, but it's just worth pointing out because it's a common error.

More advanced stuff

Sometimes you want to call the callback so it sees a specific value for this . You can easily do that with the JavaScript call function:

You can also pass arguments:

Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. You can use apply to do that:

T.J. Crowder's user avatar

  • I know it will work if i don't have any parameters like the example you wrote but when i try to pass a function with parameters it's throwing an exception and telling me the function is not defined –  Amgad Fahmi Commented Feb 3, 2010 at 9:29
  • @TiTaN: That's strange, there's nothing special about passing parameters into the callback. The callback reference you pass into your function is a function reference like any other, you can do all the normal things with it. –  T.J. Crowder Commented Feb 3, 2010 at 9:32
  • 4 @everyone who answered: I think TiTaN's problem is that he doesn't know how to pass a function that requires arguments into a callback that doesn't pass any arguments. Think setTimeout() . The answer is to wrap the callback in a closure: doSomething(function(){foo('this','should','work')}) –  slebetman Commented Feb 3, 2010 at 10:12
  • Someone point TiTaN to a thread (preferably on SO) discussing the issue above, my search-fu is weak today. –  slebetman Commented Feb 3, 2010 at 10:13
  • 1 @Webwoman - It depends on your use case. You could pass it as an argument, or include it in some kind of settings/options object, or any of several other options. –  T.J. Crowder Commented Feb 6, 2019 at 7:50

It is good practice to make sure the callback is an actual function before attempting to execute it:

Donald A Nummer Jr's user avatar

  • 21 if(typeof callback == "function") will have the same result. –  Reactgular Commented Oct 31, 2013 at 15:00
  • 24 Yes, but if there is no callback, why bother typeof-ing it? That's the point of callback && ... –  minseong Commented Dec 24, 2014 at 15:41

My 2 cent. Same but different...

K. Kilian Lindberg's user avatar

  • 9 I love this snippet ,i was searching for this –  vimal1083 Commented Mar 13, 2014 at 17:23

AlexB's user avatar

  • 7 Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. However in this case, this is a very old question with highly regarded answers already posted, it might not be worth your while answering this when there are newer questions that could do with more attention. –  SuperBiasedMan Commented Sep 7, 2015 at 10:29
  • 1 I like this answer its str8 forward demonstration of what people want to see. –  SHINIGAMI Commented Mar 23, 2020 at 19:32

==============================================

Ahmet Can Güven's user avatar

Some of the answers, while correct may be a little tricky to understand. Here is an example in layman's terms:

The callback means, "Jake" is always added to the users before displaying the list of users with console.log .

Source (YouTube)

Dan Bray's user avatar

  • Very confusing, unfortunately. –  stromyc Commented Apr 1 at 1:11

If you want to execute a function when something is done. One of a good solution is to listen to events. For example, I'll implement a Dispatcher , a DispatcherEvent class with ES6,then:

Dispatcher:

DispatcherEvent:

Happy coding!

p/s: My code is missing handle some error exceptions

Hien's user avatar

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

This is the Codepend with full example.

Eric Tan's user avatar

I hope this example will help everyone who wants to know about the callback in JS

Muhammad Atif Akram's user avatar

Functions are first class in JavaScript ; you can just pass them around.

Peter Mortensen's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript callback or ask your own question .

  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Genus 0 curves on surfaces and the abc conjecture
  • How should Form 990: Part IV Question 3 be answered?
  • How to allow just one user to use SSH?
  • Uneven Spacing with Consecutive Math Environments
  • Venus’ LIP period starts today, can we save the Venusians?
  • Why doesn’t the ARP command show the router's wireless MAC address?
  • Why was I was allowed to bring 1.5 liters of liquid through security at Frankfurt Airport?
  • I need to draw as attached image
  • Do all orbits emitting gravitational waves coalesce?
  • Is it possible to use wi-fi on phone while tethered to MacBook Pro?
  • Has technology regressed in the Alien universe?
  • A man hires someone to murders his wife, but she kills the attacker in self-defense. What crime has the husband committed?
  • Making a bracha mentally in case of doubt
  • are "lie low" and "keep a low profile" interchangeable?
  • chess game: loading images for the rooks
  • What if something goes wrong during the seven minutes of terror?
  • What is the trade union for postdocs working in Germany?
  • Specify geo location of web pages (each is different)
  • Is my encryption format secure?
  • Do temperature variations make trains on Mars impractical?
  • Can this minus operation be implemented via a quantum channel?
  • Ubuntu/Linux: Use WiFi to access a specific LPD/LPR network print server and use Ethernet to access everything else
  • Subspace proofs - Sheldon Axler's "Linear Algebra Done Right"
  • Did the English Koren-Steinsaltz Utilize an Erroneous Translation for Meilah 7b?

callback function javascript assignment

Home » JavaScript Tutorial » JavaScript Callbacks

JavaScript Callbacks

Summary : in this tutorial, you will learn about JavaScript callback functions including synchronous and asynchronous callbacks.

What are callbacks

In JavaScript, functions are first-class citizens . Therefore, you can pass a function to another function as an argument.

By definition, a callback is a function that you pass into another function as an argument for executing later.

The following defines a filter() function that accepts an array of numbers and returns a new array of odd numbers:

How it works.

  • First, define the filter() function that accepts an array of numbers and returns a new array of the odd numbers.
  • Second, define the numbers array that has both odd and even numbers.
  • Third, call the filter() function to get the odd numbers out of the numbers array and output the result.

If you want to return an array that contains even numbers, you need to modify the filter() function. To make the filter() function more generic and reusable, you can:

  • First, extract the logic in the if block and wrap it in a separate function.
  • Second, pass the function to the filter() function as an argument.

Here’s the updated code:

The result is the same. However, you can pass any function that accepts an argument and returns a boolean value to the second argument of the filter() function.

For example, you can use the filter() function to return an array of even numbers like this:

By definition, the isOdd and isEven are callback functions or callbacks. Because the filter() function accepts a function as an argument, it’s called a high-order function .

A callback can be an anonymous function, which is a function without a name like this:

In this example, we pass an anonymous function to the filter() function instead of using a separate function.

In ES6, you can use an arrow function like this:

There are two types of callbacks: synchronous and asynchronous callbacks.

Synchronous callbacks

A synchronous callback is executed during the execution of the high-order function that uses the callback. The isOdd and isEven are examples of synchronous callbacks because they execute during the execution of the filter() function.

Asynchronous callbacks

An asynchronous callback is executed after the execution of the high-order function that uses the callback.

Asynchronicity means that if JavaScript has to wait for an operation to complete, it will execute the rest of the code while waiting.

Note that JavaScript is a single-threaded programming language. It carries asynchronous operations via the callback queue and event loop .

Suppose that you need to develop a script that downloads a picture from a remote server and processes it after the download completes:

However, downloading a picture from a remote server takes time depending on the network speed and the size of the picture.

The following download() function uses the setTimeout() function to simulate the network request:

And this code emulates the process() function:

When you execute the following code:

you will get the following output:

This is not what you expected because the process() function executes before the download() function. The correct sequence should be:

  • Download the picture and wait for the download complete.
  • Process the picture.

To resolve this issue, you can pass the process() function to the download() function and execute the process() function inside the download() function once the download completes, like this:

Now, it works as expected.

In this example, the process() is a callback passed into an asynchronous function.

When you use a callback to continue code execution after an asynchronous operation, the callback is called an asynchronous callback.

To make the code more concise, you can define the process() function as an anonymous function:

Handling errors

The download() function assumes that everything works fine and does not consider any exceptions. The following code introduces two callbacks: success and failure to handle the success and failure cases respectively:

Nesting callbacks and the Pyramid of Doom

How do you download three pictures and process them sequentially? A typical approach is to call the download() function inside the callback function, like this:

The script works perfectly fine.

However, this callback strategy does not scale well when the complexity grows significantly.

Nesting many asynchronous functions inside callbacks is known as the pyramid of doom or the callback hell :

To avoid the pyramid of doom, you use promises or async/await functions.

  • A callback is a function passed into another function as an argument to be executed later.
  • A high-order function is a function that accepts another function as an argument.
  • Callback functions can be synchronous or asynchronous.

Popular Tutorials

Popular examples, reference materials, learn python interactively, js introduction.

  • Getting Started
  • JS Variables & Constants
  • JS console.log
  • JavaScript Data types
  • JavaScript Operators
  • JavaScript Comments
  • JS Type Conversions

JS Control Flow

  • JS Comparison Operators
  • JavaScript if else Statement
  • JavaScript for loop
  • JavaScript while loop
  • JavaScript break Statement
  • JavaScript continue Statement
  • JavaScript switch Statement

JS Functions

  • JavaScript Function
  • Variable Scope
  • JavaScript Hoisting
  • JavaScript Recursion
  • JavaScript Objects
  • JavaScript Methods & this
  • JavaScript Constructor
  • JavaScript Getter and Setter
  • JavaScript Prototype
  • JavaScript Array
  • JS Multidimensional Array
  • JavaScript String
  • JavaScript for...in loop
  • JavaScript Number
  • JavaScript Symbol

Exceptions and Modules

  • JavaScript try...catch...finally
  • JavaScript throw Statement
  • JavaScript Modules
  • JavaScript ES6
  • JavaScript Arrow Function
  • JavaScript Default Parameters
  • JavaScript Template Literals
  • JavaScript Spread Operator
  • JavaScript Map
  • JavaScript Set
  • Destructuring Assignment
  • JavaScript Classes
  • JavaScript Inheritance
  • JavaScript for...of
  • JavaScript Proxies

JavaScript Asynchronous

  • JavaScript setTimeout()

JavaScript CallBack Function

  • JavaScript Promise
  • Javascript async/await
  • JavaScript setInterval()

Miscellaneous

  • JavaScript JSON
  • JavaScript Date and Time
  • JavaScript Closure
  • JavaScript this
  • JavaScript use strict
  • Iterators and Iterables
  • JavaScript Generators
  • JavaScript Regular Expressions
  • JavaScript Browser Debugging
  • Uses of JavaScript

JavaScript Tutorials

Javascript setTimeout()

JavaScript Function and Function Expressions

Javascript setInterval()

  • Javascript Function apply()
  • Javascript Function call()

JavaScript Closures

A function is a block of code that performs a certain task when called. For example,

In the above program, a string value is passed as an argument to the greet() function.

In JavaScript, you can also pass a function as an argument to a function. This function that is passed as an argument inside of another function is called a callback function. For example,

In the above program, there are two functions. While calling the greet() function, two arguments (a string value and a function) are passed.

The callMe() function is a callback function.

Benefit of Callback Function

The benefit of using a callback function is that you can wait for the result of a previous function call and then execute another function call.

In this example, we are going to use the setTimeout() method to mimic the program that takes time to execute, such as data coming from the server.

Example: Program with setTimeout()

As you know, the setTimeout() method executes a block of code after the specified time.

Here, the greet() function is called after 2000 milliseconds ( 2 seconds). During this wait, the sayName('John'); is executed. That is why Hello John is printed before Hello world .

The above code is executed asynchronously (the second function; sayName() does not wait for the first function; greet() to complete).

  • Example: Using a Callback Function

In the above example, the second function does not wait for the first function to be complete. However, if you want to wait for the result of the previous function call before the next statement is executed, you can use a callback function. For example,

In the above program, the code is executed synchronously. The sayName() function is passed as an argument to the greet() function.

The setTimeout() method executes the greet() function only after 2 seconds. However, the sayName() function waits for the execution of the greet() function.

Note : The callback function is helpful when you have to wait for a result that takes time. For example, the data coming from a server because it takes time for data to arrive.

Table of Contents

  • Introduction
  • Benefits of Callback Function

Sorry about that.

Related Tutorials

JavaScript Tutorial

What is a Callback Function in JavaScript? JS Callbacks Example Tutorial

Ilenia

In JavaScript there are higher order methods and functions that accept a function as an argument. These functions used as arguments for other functions are called callback functions.

What is a callback in JavaScript?

A callback is a function passed as an argument of another function.

This means that the parent function is usually built to use any kind of function. But the callback function, on the other hand, is meant to be used in a specific case (or a restricted number of cases) in which the parent function is used.

How do you create a callback function in JavaScript?

You create a callback function just like any other function in JavaScript:

The difference between a callback function and any other function is how it's used.

A callback function is specifically built to be used as argument of another function.

So, to create a callbackFunction you need to know how the parent function uses the callback function, what arguments it passes in, and what order it passes them in.

What is an example of a callback function?

We'll now write our own callback function, as it's something you'll have to do many times. So, let's start!

A higher order function that's already integrated in the JavaScript language is the every method.

The every method is an array method, and uses a callback to check that all the elements in the array pass a certain test.

Looking at the documentation on the every method , you can see that the callback is passed three arguments: an element of the array, the index of that element, and the whole array.

So the callback function signature would be something like this:

Callback functions can be as simple or as complex as you need them to be. To create an example, we need some context.

How to write a callback function in JavaScript

So, let's say you are working with arrays of strings. You need to check if the array contains only strings that are exactly three characters long, are uppercase, contain all different letters, and that they don't repeat inside the array.

This is a pretty complex case, but maybe you will eventually need to do something like this or of equal complexity, so it's all good practice.

You can tackle one condition at a time when you build a function with so many things to check.

The first condition is that the element is a string, so, let's add it:

Next, the strings must be all uppercase, contain only letters, and be 3 characters long.

You could check these three conditions separately, or you can check them together with a regular expression that checks for exactly those three things.

Such a regular expression would look like this: /^[A-Z]{3}$/ .

Let's see what the parts of this regular expression are:

  • The characters ^ at the beginning and $ at the end are anchors. These say that the string must start and end in exactly that way. And if you use both, they restrict a string to contain only and exactly the pattern in the regular expression.
  • [A-Z] is a character class that matches any character from A to Z , so all uppercase letters.
  • {3} is a counter. This says that the previous thing must be matched exactly three consecutive times.

The regular expression explained above is the equivalent of this regular expression: /^[A-Z][A-Z][A-Z]$/ .

In this case instead of the counter {3} we have written the class [A-Z] three times.

Let's add this to the code.

If you don't like regular expressions, you can read below how to do the same checks without using a regular expression.

Then, next, we need to check if the characters are all different.

There are three characters you can use: element[0] !== element[1] && element[0] !== element[2] && element[1] !== element[2] .

But, you can also do this with a loop – a double loop actually.

The loop will work with any length, and you don't need to rewrite it for different situations.

Is it the exact same as writing the three comparisons? Let's follow the loop to check.

At first iteration we have that j=0 , and k=1 , so the first comparison is element[0] === element[1] . Then k increases, so it's j=0 and k=2 , so that is element[0] === element[2] .

At this point the inner loop stops, and the outer loop (the one with j ) goes to the next iteration. This time j=1 , and the inner loop starts at k=j+1 so at k=2 – the comparison here is element[1] === element[2] .

The inner loop has finished looping, the outer loop goes from j=1 to j=2 , the inner loop doesn't start as k = j+1 = 3 doesn't pass the k < element.length condition of the loop.

Then, the last thing we need to check is that the strings are not repeated inside the array.

We can use indexOf to check that the current one is the first appearance of element inside the array.

We would need to reference the array for this. And we have it – it's one of the arguments passed in to the callback, the array parameter.

If this is the first appearance of the string in the array, the output of indexOf will be the same as index .

If array.indexOf(element) === index is true , that means that element is present in the array for the first time at index . If it's false , an identical string is present earlier in the array.

Let's add this check to the function. And if the string has survived through all the checks, then the function can return true at the end.

And if we didn't use a regular expression?

In the code above, to check three different things, we used a regular expression: /^[A-Z]{3}$/ .

But if you don't want to work with regex, you can use the length property to check if a string is of exactly a certain length. In this case element.length === 3 to check that the string is exactly three characters long.

Next, the string must be all uppercase and contain only letters.

You can use charCodeAt for this. This method returns the ASCII code of a character, and knowing that uppercase letters have ASCII codes from 65 to 90, you can check that there are only uppercase letters.

There are three numbers to check: element.charCodeAt(0) , element.charCodeAt(1) , and element.charCodeAt(2) . They all need to be between 65 and 90. It's only three characters, but we can still use a loop.

So, that would be as below:

Let's add this to the function:

If you have come here from the link above, you can return there to continue reading how to finish the function, otherwise, please continue to the end.

How to use the example callback function

We have written the callback function. So how do you use it?

You can also use the every method inside a callback – maybe the callback to a filter method .

As a program becomes more complex, it's probably going to use proportionally more callback functions.

Why do we use callback functions in JavaScript?

Callback functions are a neat feature of JavaScript. It means we can have a general function that does something (like every that checks if every element in an array match a certain condition, filter , that removes the elements that don't match a certain condition, replace , a string method that accepts a callback to describe how to replace parts of a string, and so on) and a callback function to add specifics of that behaviour for the specific situation.

  • filter in that situation will remove the elements specified by the callback.
  • every will check that all the elements in that situation are as specified by the callback function.
  • replace will replace parts of the string in the situation in which it is used as specified by the callback.

Higher order functions add a level of abstraction to the code. We don't know (and don't need to know), how every checks every element of the array and verifies that they all pass the tests specified by the callback. We only need to know that the method accepts a callback function for that.

Callbacks are functions that are passed as arguments of other functions. You have seen an example of how to create one, and some considerations on why they are useful.

Thank you for reading!

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

A beginner’s guide to JavaScript callbacks

Before promises and async/await were introduced, asynchronous code was dealt with exclusively using the callback functions or ‘callbacks’.

Callbacks are not really a feature of JavaScript in themselves. They are rather a way of structuring regular functions to run tasks in a certain order . The method involves effectively nested a function within a function.

It is important to note that callbacks executing functions serially (i.e. one after the other). For more flexibility, such as executing asynchronous tasks in parallel, promises are a better solution.

Executing three tasks in order 1️⃣→2️⃣→3️⃣

In a previous post on asynchronous JavaScript , we used the following example to demonstrate that tasks do not always complete in the order we want them to:

Callbacks are a solution to the puzzle of how we can solve this problem of ordering using functions.

First, we wrap each setTimeout in a function so we can call them and pass in a parameter when doing so.

The way callbacks work is that the passed in parameter will be a function (defined when called). This passed in function should be called after the original function has completed it task.

Making these changes to the example above produces the following:

By convention, the new parameter is called callback (but it can be named something else without changing the functionality).

They are now serially executed in the correct order!

Just to be clear, here is what is going on in the above code, step-by-step:

  • First, we call firstTask . JavaScript runs the content of firstTask , which ends with callback() . This calls the function we passed in as the first parameter of firstTask . Inside this function, we call secondTask .
  • JavaScript now runs the content of secondTask , ending with callback() . This runs the function that we pass in as an argument to secondTask . Within the function, we call thirdTask.
  • thirdTask is the final function we run. Because of this, we did not include a callback parameter in its definition and do not pass in any argument.

Error-handling ⚠️

In the example above we have not included error-handling. But in a real-world situation, this would need to be included, too.

We first need to make some changes to the task functions. Namely, we add a parameter to each callback function (called error or err by convention).

If there is an error when we call the function, we want the value of error to be information about the error. If there is no error, we want the value to be null (falsy). This information is passed to the callback function and we can check for the error there.

But first, here is how our functions look with error-handling incorporated:

Notice that to simulate a possible error, we now create a random number between 1 and 10 at the beginning of each function. And then we create an IF statement that runs error handling if the number generated is 1 and otherwise runs the task.

Now we call the functions as before but now check the error parameter in each callback function using an IF statement. If it contains something, we have an error and log this to the console. Otherwise we log a message to the console that the task was completed successfully:

You may wonder why there is no error-checking within thirdTask . This is because it is the final task and so the error is handled within the thirdTask function itself (not a callback).

Callback function drawbacks

#1: callback 'hell' 😈🔥⬅🏃.

Notice an emerging problem with the coding above?

The subjective but well-recognized problem with callbacks is nesting. Namely, once there are several nested callbacks, it is easy to lose our way in our code – especially if there is error-handling.

The example above of three nested tasks is already going this way. But in a real project, there may be many more tasks to run in sequence.

The below would certainly qualify as callback hell or the pyramid of doom :

Because of the nesting problem, this type of code for handing multiple asynchronous tasks increasingly frowned upon, especially in light of more appropriate alternatives (promises and async-await syntax).

#2: Flexibility

Callback hell grabs all the headlines but the lack of flexibility of callbacks in handling asynchronous code if just as important.

For example, what if we want the third task to wait for the completion of the first and second task but don't care about the order the first and second tasks complete in?

In the earlier example in this article, the second task waits for the completion of the first task. If we do not care about the ordering of the first and second task, this is inefficient: we would like them both to start executing immediately and call the third task as soon as both are done. But we cannot do this using the callbacks frameworks because tasks are executed one at a time (serially).

For more sophisticated sequencing, we would need to use promises or async-await.

Callbacks provide a solution to the problem of asynchronous code execution. They execute code statements serially and are a useful solution when wanting to order a limited number of tasks.

But working with callbacks soon becomes cumbersome when there are more than two processes to order (especially if error-handling is required). Moreover, if the sequencing of tasks should be more complex than serial, other techniques are needed, such as promises or the promise-based async-await syntax.

Related links and resources:

  • Mozilla MDN Web Docs: Callback function
  • W3Schools reference: JavaScript Callbacks

Related Posts:

An old telephone

callback function javascript assignment

Callback Functions in JavaScript: A Comprehensive Guide

Aquib Afzal

Aquib Afzal

Bits and Pieces

In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some operation has been completed.

Callbacks allow us to write asynchronous code, where we can continue to execute other code while waiting for a particular event to occur.

How Do Callback Functions Work?

Callback functions are used to handle events that may occur at any point in time. By passing a callback function as an argument, we allow the function to call it when necessary.

For example, we have to execute doSomethingElse function just after logging “Doing something…” which is in function doSomething .

In this example, we define two functions, doSomething and doSomethingElse . The doSomething function takes a callback function as an argument and logs a message to the console. It then calls the callback function. The doSomethingElse function logs a different message to the console.

Finally, we call the doSomething function and pass in the doSomethingElse function as the callback. When doSomething is called, it logs "Doing something..." to the console and then calls the doSomethingElse function, which logs "Doing something else..." to the console.

Real-World Example

Another real-world example of using a callback function is when fetching data from a server. In this case, we use a callback function to handle the data once it has been received.

In this example, we define a function fetchData that takes a URL and a callback function as arguments. The function uses the fetch function to make a network request to the specified URL. Once the data is received, it is converted to JSON and the callback function is called with the data as an argument.

Finally, we call the fetchData function and pass in a callback function that logs the data to the console. When the data is received from the server, the callback function is called with the data, and the data is logged to the console.

Issues with Callback Functions and Solutions

One issue that can arise when using callback functions is the problem of “ callback hell ” or “ pyramid of doom .” This occurs when you have multiple nested callbacks, making the code difficult to read and understand.

One solution to this problem is to use promises or async/await , which allow for more structured and readable code.

Callbacks are a powerful tool in programming, allowing for asynchronous code execution and enabling developers to write more efficient and flexible code.

However, they can also make code difficult to read and understand, especially when there are multiple nested callbacks.

Promises and async/await are two alternatives to using callbacks that can make code more readable and maintainable.

Some Quick Links

JsFramework | CleanCode | LocalStorage | Redis Caching | Node.js Cluster | Array Methods | Callback Function | Promise | Async/Await

LinkedIn | Github

Build Apps with reusable components, just like Lego

Bit ’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

→ Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

→ Micro-Frontends

→ design system, → code-sharing and reuse, how we build micro frontends, building micro-frontends to speed up and scale our web development process..

blog.bitsrc.io

How we Build a Component Design System

Building a design system with components to standardize and scale our ui development process., how to reuse react components across your projects, finally, you completed the task of creating a fantastic input field for the newsletter in your app. you are happy with…, 5 ways to build a react monorepo, build a production-grade react monorepo: from fast builds to code-sharing and dependencies., how to create a composable react app with bit, in this guide, you’ll learn how to build and deploy a full-blown composable react application with bit. building a…, sharing javascript utility functions across projects, so you’ve built that awesome utility function and put in a few hours on it. some months later, you realized you needed….

Aquib Afzal

Written by Aquib Afzal

Software Developer @ Encora Inc. | Blogger | talks about #javascript #react #nodejs #performance #webdevelopment

Text to speech

IMAGES

  1. What Are Callback Functions In JavaScript?

    callback function javascript assignment

  2. What are Callback Functions in JavaScript and How to use JS CallBacks?

    callback function javascript assignment

  3. WHAT IS A CALLBACK FUNCTION IN JAVASCRIPT?

    callback function javascript assignment

  4. How to Use Callback Functions in JavaScript: A Complete Guide with

    callback function javascript assignment

  5. What are Callback Functions in JavaScript and How to use JS CallBacks?

    callback function javascript assignment

  6. Callback functions in Javascript explained

    callback function javascript assignment

COMMENTS

  1. JavaScript Callbacks - W3Schools

    JavaScript Callbacks. A callback is a function passed as an argument to another function. Using a callback, you could call the calculator function ( myCalculator ) with a callback ( myCallback ), and let the calculator function run the callback after the calculation is finished:

  2. JavaScript Callback Functions – What are Callbacks in JS and ...

    In JavaScript, the way to create a callback function is to pass it as a parameter to another function, and then to call it back right after something has happened or some task is completed. Let’s see how…

  3. Create a custom callback in JavaScript - Stack Overflow

    All I need to do is to execute a callback function when my current function execution ends. function LoadData() {. alert('The data has been loaded'); //Call my callback with parameters. For example, //callback(loadedData , currentObject); }

  4. Introduction: callbacks - The Modern JavaScript Tutorial

    Let’s add a callback function as a second argument to loadScript that should execute when the script loads: function loadScript(src, callback) { let script = document.createElement('script'); . script. src = src; script.onload = () => callback(script); . document. head.append( script); }

  5. An Essential Guide to JavaScript Callbacks - JavaScript Tutorial

    How it works. First, define the filter() function that accepts an array of numbers and returns a new array of the odd numbers. Second, define the numbers array that has both odd and even numbers. Third, call the filter() function to get the odd numbers out of the numbers array and output the result.

  6. What is a Callback Function in JavaScript? - freeCodeCamp.org

    A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

  7. JavaScript CallBack Function - Programiz

    The benefit of using a callback function is that you can wait for the result of a previous function call and then execute another function call. In this example, we are going to use the setTimeout() method to mimic the program that takes time to execute, such as data coming from the server.

  8. What is a Callback Function in JavaScript? JS Callbacks ...

    You create a callback function just like any other function in JavaScript: function callbackFunction () { } The difference between a callback function and any other function is how it's used. A callback function is specifically built to be used as argument of another function.

  9. A beginner's guide to JavaScript callbacks - OpenJavaScript.info

    Learn how to structure several tasks to complete in a specified order using JavaScript callback functions.

  10. Callback Functions in JavaScript: A Comprehensive Guide - Medium">Callback Functions in JavaScript: A Comprehensive Guide - Medium

    In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Callbacks allow us to write asynchronous code, where we can continue to execute other code while waiting for a particular event to occur.