{"id":1387,"date":"2021-11-12T07:18:50","date_gmt":"2021-11-12T13:18:50","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=1387"},"modified":"2022-04-25T09:38:10","modified_gmt":"2022-04-25T14:38:10","slug":"javascript-callback-functions","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/","title":{"rendered":"The Ultimate Guide to Callback Functions in JavaScript"},"content":{"rendered":"\n<p>Callback functions are one of those concepts every JavaScript developer should understand. Getting an understanding of what they are and how to use them is often a common problem for beginner programmers learning asynchronous concepts of JavaScript. In this article, we are going to turn this complex concept simple.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Understanding_What_Callbacks_Are\" >Understanding What Callbacks Are<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#How_to_Use_Callback_Functions\" >How to Use Callback Functions<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Anonymous_Function_Callbacks\" >Anonymous Function Callbacks<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Callback_Functions_using_ES6_Syntax\" >Callback Functions using ES6 Syntax<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Order_of_Callback_Execution\" >Order of Callback Execution<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Types_of_Callback_Functions\" >Types of Callback Functions<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Synchronous_Callbacks\" >Synchronous Callbacks<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Be_Aware_of_Performance_or_Blocking_Callbacks\" >Be Aware of Performance or Blocking Callbacks<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Asynchronous_Callbacks\" >Asynchronous Callbacks<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Are_Callback_Functions_Dead\" >Are Callback Functions Dead?<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Popular_Callback_Functions_used\" >Popular Callback Functions used<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Why_Callback_Functions_Are_Important\" >Why Callback Functions Are Important<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-callback-functions\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Understanding_What_Callbacks_Are\"><\/span>Understanding What Callbacks Are<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>Callbacks are functions in JavaScript that are passed as arguments to another function and are triggered or executed inside that other function<\/strong>. <strong>Callback functions are generally triggered after all statements in another function are executed.<\/strong> Let&#8217;s take a look a look at the following illustration to visualize this concept.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/How-Callback-Functions-Work.png\" alt=\"\" class=\"wp-image-1389\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-Callback-Functions-Work.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-Callback-Functions-Work-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-Callback-Functions-Work-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>How callback functions work<\/figcaption><\/figure><\/div>\n\n\n\n<p>In the previous image, we have two functions: <code>function A()<\/code> and <code>function B()<\/code>, in which <code>function A()<\/code> is triggered inside <code>function B()<\/code> when we pass <code>function A()<\/code> as an argument of <code>function B()<\/code>.<\/p>\n\n\n\n<p>The concept of callbacks can become confusing among beginner JavaScript programmers as it sounds confusing the idea of passing a function as a parameter. In JavaScript, you can pass any argument to a function regardless of whether it is a string, a number, an array, an undefined value, a null value, and also a function as you saw with the concept of callbacks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_to_Use_Callback_Functions\"><\/span>How to Use Callback Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now that you understand what callback functions are, it is time to put that knowledge and write some code. Initially, we are going to translate the example you saw in the previous image into code.<\/p>\n\n\n\n<p>Let&#8217;s take a look at how a callback function would look in code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ define function to be used as a callback function\nfunction A() {\n   console.log('function A');\n}\n\n\/\/ define function that triggers callback function\nfunction B(callback) {\n   callback();\n}\n\n\/\/ execute function that triggers callback function\nB(A); \/\/ expected log: 'function A'<\/code><\/pre>\n\n\n\n<p>In this example, we are defining two functions <code>A<\/code> and <code>B<\/code>, which <code>function B<\/code> is the one executing <code>function A<\/code>. You can pass any callback function to <code>function B<\/code>. <\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function Z() {\n   console.log('function Z');\n}\n\nfunction X() {\n   console.log('function X');\n}\n\nfunction Y() {\n   console.log('function Y');\n}\n\nB(Z); \/\/ expected log: 'function Z'\nB(X); \/\/ expected log: 'function X'\nB(Y); \/\/ expected log: 'function Y'<\/code><\/pre>\n\n\n\n<p>Notice how in this example, we defined functions <code>Z<\/code>, <code>X<\/code>, and <code>Y<\/code> and passed them as callback functions inside <code>function B<\/code> resulting in the execution of a different logic every time.<\/p>\n\n\n\n<p>You can also pass and define a callback function at the same time.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>B(\n  function W() {\n     console.log('function W');\n  }\n); \/\/ expected log: 'function W'<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Anonymous_Function_Callbacks\"><\/span>Anonymous Function Callbacks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>It is also possible to pass an anonymous function as a callback. Remember, <strong>anonymous functions are functions without a specific name<\/strong>. Let&#8217;s take the previous example, and remove the <code>W<\/code> to automatically make the function anonymous.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>B(\n  function () {\n     console.log('anonymous function');\n  }\n); \/\/ expected log: 'anonymous function'<\/code><\/pre>\n\n\n\n<p>Defining the function when passing it as an argument is possible, it is not recommended to do this practice as it provides two problems:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Code is confusing and hard to understand<\/li><li>Cannot call <code>function W<\/code> or the anonymous function outside of a <code>function B<\/code><\/li><\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Callback_Functions_using_ES6_Syntax\"><\/span>Callback Functions using ES6 Syntax<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>ES6 allows for generating arrow function expressions. <strong>Arrow function expressions allow defining a function without the need of using the keyword <code>function<\/code> while also using the expression <code>=&gt;<\/code> between the arguments and the body brackets<\/strong>. Let&#8217;s check how they look when used as callbacks.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ calbacks defined using arrow function expressions\nB(\n  () =&gt; {\n     console.log('anonymous function');\n  }\n); \/\/ expected log: 'anonymous function'\n\nB(\n  () =&gt; console.log('one liner anonymous function')\n); \/\/ expected log: 'one liner anonymous function'\n\nconst anotherOneLinerFn = () =&gt; console.log('another one liner anonymous function');\nB(anotherOneLinerFn); \/\/ expected log: 'another one liner anonymous function'<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Order_of_Callback_Execution\"><\/span>Order of Callback Execution<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>All of our previous examples can make new programmers wonder whether there is a real need for function B to be defined in the first place as the only thing it does is execute callbacks.<\/p>\n\n\n\n<p><em>Why not call the function directly instead of a callback?<\/em><\/p>\n\n\n\n<p>Remember, we can add any additional logic to the function executing all the callbacks. Hence, if we decide to modify <code>function B<\/code> to execute other logic, we can do it and still execute the callback functions.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ modifying logic of the function that triggers callback function\nfunction B(callback) {\n   \/\/ function's B internal logic\n   const date = new Date();\n   console.log('This is the year ' + date.getFullYear());\n   \n   \/\/ execute callback function at the end\n   callback();\n}<\/code><\/pre>\n\n\n\n<p>In that way, regardless of what callback function is passed to <code>function B<\/code>, function B will always log <code>This is the year ${currentYear}<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>B(A); \n\/\/ expected result\n\/\/ expected log: 'This is the year 2021'\n\/\/ expected log: 'function A'\n\nB(Y); \n\/\/ expected result\n\/\/ expected log: 'This is the year 2021'\n\/\/ expected log: 'function Y'\n\nB(X); \n\/\/ expected result\n\/\/ expected log: 'This is the year 2021'\n\/\/ expected log: 'function X'<\/code><\/pre>\n\n\n\n<p>Notice how callback functions are executed at the end of <code>function B<\/code>. However, you can modify the logic to best fit your solution. As mentioned in the beginning, <strong>it is common to execute callback functions at the end of a function<\/strong>, <strong>but they don&#8217;t have to be executed at the end of a function all the time<\/strong>. It is possible to trigger callback functions at the top, middle, or end of any other function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ modifying logic of the function that triggers callback function\nfunction B(callback) {\n   \/\/ execute callback function right away prior executing additional logic\n   callback();\n\n   \/\/ function's B internal logic\n   const date = new Date();\n   console.log('This is the year ' + date.getFullYear()); \n   \n}<\/code><\/pre>\n\n\n\n<p>By moving the position where the callback is triggered, the result will change whenever we trigger <code>function B<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>B(A); \n\/\/ expected result\n\/\/ expected log: 'function A'\n\/\/ expected log: 'This is the year 2021'\n\nB(Y); \n\/\/ expected result\n\/\/ expected log: 'function Y'\n\/\/ expected log: 'This is the year 2021'\n\nB(X); \n\/\/ expected result\n\/\/ expected log: 'function X'\n\/\/ expected log: 'This is the year 2021'<\/code><\/pre>\n\n\n\n<p>Callback functions will execute as long as you call them inside another function. Otherwise, callback functions will never run their logic. You can see this in the following <code>function C<\/code> definition.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>\/\/ function accepting callback function, but doesn't execute callback function\nfunction C(callback) {\n   \/\/ function's C internal logic\n   console.log('Function C is not calling any callbacks'); \n}<\/code><\/pre>\n\n\n\n<p>If we decide to trigger <code>function C<\/code> with different callback functions such as <code>A<\/code>, <code>Z<\/code>, <code>X<\/code>, or <code>Y<\/code>, we will always get the same output.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>C(A); \nC(Z);\nC(X);\nC(Y);\n\n\/\/ expected results\n\/\/ expected log: 'Function C is not calling any callbacks<\/code><\/pre>\n\n\n\n<p>With this last example, you can visualize the power of callbacks. <strong>It allows running the same internal logic of a function while also triggering a callback function that adds additional functionality to an existing function without explicitly defining such functionality inside the function<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Types_of_Callback_Functions\"><\/span>Types of Callback Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>There are two types of callback functions: synchronous and asynchronous. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Synchronous_Callbacks\"><\/span>Synchronous Callbacks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong>Synchronous callbacks are triggered sequentially in another function following the order of operations defined insider another function<\/strong>. Unless the callback execution is completed, they prevent other functions from calling callbacks to complete all its internal logic. Let&#8217;s take a look at the following diagram.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Synchronous-Callbacks.png\" alt=\"\" class=\"wp-image-1394\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Synchronous-Callbacks.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Synchronous-Callbacks-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Synchronous-Callbacks-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>Synchronous Callbacks<\/figcaption><\/figure><\/div>\n\n\n\n<p>As you noticed, the <code>getCurrentMonth<\/code> function executes four different processes:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Get Current Date<\/li><li>Log Current Date<\/li><li>Execute Callback<\/li><li>Return Month<\/li><\/ol>\n\n\n\n<p>In code, this would look something along the following lines:<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function getCurrentMonth(callback) {\n   \/\/ Get Current Date\n   const date = new Date();\n\n   \/\/ Log Current Date\n   console.log('This is the current Date' + date.toString());\n   \n   \/\/ execute callback function\n   callback();\n\n   return date.getMonth() + 1;\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Be_Aware_of_Performance_or_Blocking_Callbacks\"><\/span>Be Aware of Performance or Blocking Callbacks<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p>Synchronous callbacks are used most of the time. However, if <strong>the callback functions are not performant, they will also affect the performance of functions executing the callback function.<\/strong> Let&#8217;s take a look at the following code<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function goodPerformanceFn() {\n  console.log('good performance');\n}\n\nfunction badPerformanceFn() {\n  for (var p = 0; p &lt; 1000; p++) {\n    console.log('bad performance');\n  }\n}\n\nfunction getCurrentMonth(callback) {\n   const t0 = performance.now();\n\n   \/\/ Get Current Date\n   const date = new Date();\n\n   \/\/ Log Current Date\n   console.log('This is the current Date' + date.toString());\n   \n   \/\/ execute callback function\n   callback();\n\n   \/\/ log how long it took to trigger all processes prior returning month\n   const t1 = performance.now();\n   console.log('Took: ' + (t1 - t0) + 'msecs');\n   \n   return date.getMonth() + 1;\n}\n\ngetCurrentMonth(goodPerformanceFn);\ngetCurrentMonth(badPerformanceFn);<\/code><\/pre>\n\n\n\n<p>If we execute this piece of code in a terminal or in the console of the browser&#8217;s developer tools, you will see how long it takes each process triggered by <code>getCurrentMonth<\/code> function to complete.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"697\" height=\"266\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Problems-with-Synchronous-Callback-Function-JavaScript-1.png\" alt=\"\" class=\"wp-image-1400\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Problems-with-Synchronous-Callback-Function-JavaScript-1.png 697w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Problems-with-Synchronous-Callback-Function-JavaScript-1-300x114.png 300w\" sizes=\"auto, (max-width: 697px) 100vw, 697px\" \/><figcaption>Problems with Synchronous Callback Functions in JavaScript<\/figcaption><\/figure><\/div>\n\n\n\n<p> When executing the callback function <code>goodPerformanceFn<\/code>, it took 0.3msecs for the <code>getCurrentMonth<\/code> to complete its execution. <\/p>\n\n\n\n<p>On the other hand, it took 95.4msec for the <code>getCurrentMonth<\/code> to complete its execution when calling <code>badPerformanceFn<\/code> callback function. It took 95 times longer for <code>getCurrentMonth<\/code> to complete.<\/p>\n\n\n\n<p>Processes that take a long time to complete their execution <a href=\"https:\/\/www.becomebetterprogrammer.com\/is-node-js-single-threaded-or-multi-threaded-and-why\/#Dont_Block_the_Event_Loop_aka_the_Main_Thread\">block the loop<\/a>. This is antipattern and it should be avoided unless it is absolutely necessary for a callback function process to finish.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Asynchronous_Callbacks\"><\/span>Asynchronous Callbacks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p><strong>Asynchronous callbacks are used to prevent blocking code execution inside the function calling a callback<\/strong>. <\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Asynchronous-Callbacks.png\" alt=\"\" class=\"wp-image-1401\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Asynchronous-Callbacks.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Asynchronous-Callbacks-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Asynchronous-Callbacks-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>Asynchronous callbacks<\/figcaption><\/figure><\/div>\n\n\n\n<p>If you remember our previous example, function <code>getCurrentMonth<\/code> was calling <code>badPerformanceFn<\/code> which took a lot of time affecting the performance of <code>getCurrentMonth<\/code>.<\/p>\n\n\n\n<p>Let&#8217;s create another function called <code>reFactoredBadPerformanceFn<\/code> which a refactored version of the <code>badPerformanceFn<\/code> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function reFactoredBadPerformanceFn() {\n  setTimeout(function () {\n    for (var p = 0; p &lt; 1000; p++) {\n      console.log('refactored bad performance');\n    }\n  }, 0)\n}\n\ngetCurrentMonth(reFactoredBadPerformanceFn)<\/code><\/pre>\n\n\n\n<p>Now, we won&#8217;t have to wait to get the month returned when triggering the <code>getCurrentMonth<\/code> with the callback <code>reFactoredBadPerformanceFn<\/code>.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"522\" height=\"134\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Better-Perfomance-with-Asynchronous-Callbacks.png\" alt=\"\" class=\"wp-image-1402\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Better-Perfomance-with-Asynchronous-Callbacks.png 522w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Better-Perfomance-with-Asynchronous-Callbacks-300x77.png 300w\" sizes=\"auto, (max-width: 522px) 100vw, 522px\" \/><\/figure><\/div>\n\n\n\n<p>If you are not very experienced with <code>setTimeout<\/code>, you might be confused as the timeout parameter is set to 0, which logically means to wait 0 milliseconds to execute the internal function handler. In theory, that is correct, but there is a catch.<\/p>\n\n\n\n<p>Executing <code>setTimeout(fn, 0)<\/code> doesn&#8217;t guarantee the function will execute right away. In order to understand what is going on, we need to understand what the event loop is.<br><br><strong>The event loop is a mechanism used by JavaScript in charge of executing code and the reason behind JavaScript&#8217;s asynchronous programming<\/strong>. Let&#8217;s check the following diagram.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Event-Loop-2.png\" alt=\"\" class=\"wp-image-1405\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Event-Loop-2.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Event-Loop-2-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Event-Loop-2-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>JavaScript Event Loop<\/figcaption><\/figure><\/div>\n\n\n\n<p>What happens is JavaScript executes processes that are placed in the call stack. In the case of the <code>getCurrentMonth<\/code> function, there will be the following processes inside the call stack:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Get Current Date<\/li><li>Log Current Date<\/li><li>Execute Callback<\/li><li>Return Month<\/li><\/ul>\n\n\n\n<p>Once the call stack finishes executing all of these processes from the <code>getCurrentMonth<\/code> function, the stack will be empty and it will pick any functions lined up in the callback queue based on the order they arrive. <\/p>\n\n\n\n<p>When the call stack encounters an asynchronous operation, it sends that operation to the browser API or web API. This API will start a different thread to run those asynchronous operations. This prevents blocking the normal execution of processes in the call stack.<\/p>\n\n\n\n<p>Once those asynchronous operations are completed, they are sent to the callback queue and eventually back to the call stack as soon as all the functions in front of the asynchronous operation response are picked and executed in the call stack. The method <code>setTimeout<\/code> is considered an asynchronous operation. Therefore, the event loop will move the <code>setTimeout<\/code> from the call stack to the Web API&#8217;s own thread and prevent from blocking other operations in the call stack.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/How-async-operations-are-handled-in-the-event-loop.png\" alt=\"\" class=\"wp-image-1406\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-async-operations-are-handled-in-the-event-loop.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-async-operations-are-handled-in-the-event-loop-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/How-async-operations-are-handled-in-the-event-loop-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>Moving the TimeHandler function once the minimum timeout has completed inside the Web API&#8217;s thread <\/figcaption><\/figure><\/div>\n\n\n\n<p>Then the <code>setTimeout<\/code> will trigger the TimeHandler callback function defined as the first parameter <code>setTimeout(timeHandler, timeout)<\/code>. If you remember the <code>setTimeout<\/code> we had defined in the<code>reFactoredBadPerformanceFn<\/code> function, we log several messages using a loop.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function reFactoredBadPerformanceFn() {\n  setTimeout(function () {\n    for (var p = 0; p &lt; 1000; p++) {\n      console.log('refactored bad performance');\n    }\n  }, 0)\n}<\/code><\/pre>\n\n\n\n<p>Hence, each of those logs will execute in the call stack until they are all completed.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"800\" height=\"500\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Triggering-Timer-Handler.png\" alt=\"\" class=\"wp-image-1407\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Triggering-Timer-Handler.png 800w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Triggering-Timer-Handler-300x188.png 300w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Triggering-Timer-Handler-768x480.png 768w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/><figcaption>Executing Processes from the TimeHandler function<\/figcaption><\/figure><\/div>\n\n\n\n<p>Another example of an asynchronous callback is using the <code>fetch<\/code> method to make a request to an API.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function fetchData() {\n  return fetch('https:\/\/dog.ceo\/api\/breeds\/image\/random')\n    .then((response) =&gt; response.json())\n    .then((data) =&gt; {\n      console.log('Got the data ', data );\n      return data;\n    });\n}\n\ngetCurrentMonth(fetchData);<\/code><\/pre>\n\n\n\n<p>That&#8217;s why, we don&#8217;t need to wait to get the current month from <code>getCurrentMonth<\/code> function when triggering <code>fetchData<\/code> as a callback function.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"678\" height=\"164\" src=\"https:\/\/www.becomebetterprogrammer.com\/wp-content\/uploads\/2021\/11\/Fetch-asynchronous-callback.png\" alt=\"\" class=\"wp-image-1408\" srcset=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Fetch-asynchronous-callback.png 678w, https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-content\/uploads\/2021\/11\/Fetch-asynchronous-callback-300x73.png 300w\" sizes=\"auto, (max-width: 678px) 100vw, 678px\" \/><figcaption>Example of Performance Using Async Callback Function<\/figcaption><\/figure><\/div>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Are_Callback_Functions_Dead\"><\/span>Are Callback Functions Dead?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>Callback functions are not dead. In fact, there is a high chance you have been using them without even realizing they were called callback functions<\/strong>. A good example of this is when you need to find a specific element in an array.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5]\n\nconst numberFound = numbers.find((number) =&gt; number === 1);\n\nconsole.log('number found ', numberFound);<\/code><\/pre>\n\n\n\n<p>Probably you didn&#8217;t notice it was a callback as it was written using an arrow function expression. However, we could still write using the typical <code>function<\/code> keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5];\n\nconst numberFound = numbers.find(\n  function (number) { \n    return number === 1\n  }\n);\n\nconsole.log('number found ', numberFound);<\/code><\/pre>\n\n\n\n<p>You could assign a variable to the callback function as we do in this case for <code>findNumber<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1,2,3,4,5]\n\nconst findNumber = function (number) { \n    return number === 1\n };\n\nconst numberFound = numbers.find(findNumber);\n\nconsole.log('number found ', numberFound);<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Popular_Callback_Functions_used\"><\/span>Popular Callback Functions used<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Some of the most popular callback functions that are used come from using array methods.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>string.replace(callback)<\/code><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><code>array.forEach(callback)<\/code><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><code>array.find(callback)<\/code><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><code>array.some(callback)<\/code><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><code>array.filter(callback)<\/code><\/li><\/ul>\n\n\n\n<ul class=\"wp-block-list\"><li><code>array.reduce(callback)<\/code><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_Callback_Functions_Are_Important\"><\/span>Why Callback Functions Are Important<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>Callbacks are important because they allow you to define a process that should execute happen whenever a behavior gets triggered<\/strong>. If you are a front-end developer, an example of common behaviors you need to pass a callback function is when executing functions triggered by a DOM event. This could be:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>onclick: The event occurs when the user clicks on an element<\/li><li>onfocus: The event occurs when an element gets focus<\/li><li>onblur: The event occurs when an element loses focus<\/li><\/ul>\n\n\n\n<p>However, <a href=\"https:\/\/www.w3schools.com\/jsref\/dom_obj_event.asp\" target=\"_blank\" rel=\"noreferrer noopener\">there are more DOM events that can be wired up with callbacks<\/a>.<\/p>\n\n\n\n<p>A good way to think about this is whenever your boss tells you to call her back whenever you finish the development of a feature to assign you a new task. It would be pointless to call your boss when the development of the feature isn&#8217;t completed as she won&#8217;t give you another task until the current task is completed.<\/p>\n\n\n\n<p>The same we can say about callbacks. We can tell the applications to open a modal whenever a user clicks on a &#8220;create account&#8221; button, or display error messages whenever an input loses focus and there is an invalid value for an email field.<\/p>\n\n\n\n<p><a href=\"https:\/\/nodejs.org\/en\/knowledge\/getting-started\/control-flow\/what-are-callbacks\/\" target=\"_blank\" rel=\"noreferrer noopener\">Those familiar working with Node.js, which allows developing backend\/API solutions with JavaScript, callbacks are used all the time<\/a>. Due to the nature of JavaScript, processes are executed sequentially, one after another. <\/p>\n\n\n\n<p>If we were to have a NodeJS API with two API endpoints and two people are making a request to two different endpoints at the same time, what happens behind the scenes is that one person will be the first executing an endpoint, and the other person will be next in the line to execute an endpoint as there is really no such thing as having two requests running at the same time for NodeJs.<\/p>\n\n\n\n<p>Can you imagine how long will the second person have to wait in case the first person reaching an API endpoint takes a lot of time to get a response? Subsequently, the second person will have to wait for the first process to execute which was triggered by someone else, but also the process the second person intended to trigger in the first place. <\/p>\n\n\n\n<p>In other words, one process is blocking the other.<\/p>\n\n\n\n<p>That&#8217;s why, it is critical for NodeJS to not wait for processes like I\/O to finish, but instead define callbacks that will trigger once these asynchronous processes finish using the event loop smart mechanism to prevent blocking the call stack.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All in all, callback functions are typically used to execute asynchronous processes when a task completes in JavaScript. Chances are you have used callbacks before without knowing about it if you use methods such as <code>array.forEach<\/code> or <code>myString.toReplace<\/code>. <\/p>\n\n\n\n<p>However, be careful to avoid using callbacks without understanding the implications they could have in the performance of a program, especially when executing callbacks that block the event loop.<\/p>\n\n\n\n<p><strong>Was this article helpful?<\/strong><\/p>\n\n\n\n<p>Share it with other developers who want an in-depth and simple explanation about callbacks. You can also share your thoughts by replying on Twitter of <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1459150572565798916\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a> or to my personal account.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">Blog article announcement!<br><br>At this time, we are going to be talking explaining a concept hard to understand when starting learning about JavaScript: Callbacks.<a href=\"https:\/\/t.co\/4uchD7dKBr\">https:\/\/t.co\/4uchD7dKBr<\/a><a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a> <a href=\"https:\/\/twitter.com\/hashtag\/webdevelopment?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#webdevelopment<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1459150572565798916?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">November 12, 2021<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Callbacks are functions in JavaScript that are passed as arguments to another function and are triggered or executed inside that other function.<\/p>\n","protected":false},"author":1,"featured_media":1447,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16,14],"tags":[],"class_list":["post-1387","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","category-tutorial","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1387","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=1387"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1387\/revisions"}],"predecessor-version":[{"id":2479,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/1387\/revisions\/2479"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/1447"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=1387"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=1387"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=1387"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}