Javascript Callbacks

Javascript callback is a function passed into another function as an argument to be executed later. Suppose following is the number array:-

     let numbers = [1, 2, 7, 3, 4, 6]; 

To find all the odd numbers in the array, we can use the filter() method of the Array object. The filter() method creates a new array with the elements that pass the test implemented by a function.

When we pass a callback function into another function, we just pass the reference of the function i.e., the function name without the parentheses ().

To make it shorter, we can use an anonymous function as a callback.

Input:- 
    <body>   
    	<button id="save_btn">Save</button>
    	<script>
            function btnClicked() { 
            	alert("Button clicked!");
        	    }
        	    let btn = document.querySelector('#save_btn');
            btn.addEventListener('click',btnClicked);
    	</script> 
	 </body>

Output:-


Synchronous callback functions

If our code executes sequentially from top to bottom, it is synchronous.

In the following example, the arrow function is a callback function used in a synchronous function and sort() method completes first before the console.log() executes.

Input:- 
    <script>
        function btnClicked() { 
           alert("Button clicked!");
        	}
        	let btn = document.querySelector('#save_btn');
        btn.addEventListener('click',btnClicked);
   </script> 

Output:-


Asynchronous callback functions

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

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

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

The following code uses the setTimeout() function to simulate the download() function:-

Input:- 
    <script>
        function download(url, callback) {
            setTimeout(() => {
                document.write(`Downloading ${url} ...` + "<br/>");
                callback(url);
            }, 3000);
        }
        function process(picture) {
            document.write(`Processing ${picture}` + "<br/>");
        }
        let url = 'https://www.google.com/pic.jpg';
        download(url, process);	
	  </script> 

Output:-