Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 27, 2023 12:53 am

How to Use Callback Functions in JavaScript and ES6


If you’re familiar with programming, you’ve certainly used functions. A function is a chunk of code that you can use over and over again to perform a given task in your program, rather than writing the code multiple times.


But what is a callback function?


Callback functions are an integral part of JavaScript. They’re commonly when performing to network requests, reacting to page-related events, and using code from a third-party library. If you want to be adept at writing JavaScript, you’ll need to master callbacks.


If you’re looking to learn the ins and outs of JavaScript callback functions, including ES6 arrow functions, then this article is for you. We’ll learn how to define callback functions in JavaScript by going through some examples.


What is a Callback Function?


A function can accept one or more values (as parameters). The value can be a string, number, boolean, null, object, or even another function. That last one is a callback—a function passed into another function as a parameter.


Here’s an example:















1
function log(getMessage) {  
2
    getMessage();
3
}

The log( ) function takes in getMessage as a parameter and calls getMessage() inside its body. This is perfectly valid in JavaScript and the function within log()'s body is called a “callback” function.


The Purpose of Callback Functions


JavaScript is a synchronous language, meaning it executes code in a sequential manner (one after the other, from top to bottom). However, in some cases, the code is to be executed in response to an event, and not in a sequential way. This is called asynchronous programming.


Callbacks are used to execute code right after something else has happened. A callback function will never run until the main function is fully executed, so we can use them to create asynchronous code in our programs and control the flow of code execution.


How to Create a Callback Function


In JavaScript, the way to create a callback function is to pass it as a parameter to another function. Inside the function, we then execute the callback after something has happened or some task is completed.


Assuming we want to print a message on the terminal console after four seconds have passed, we can do so by passing a callback function to the setTimeout() function: 























1
const message = function() {  
2
    console.log("This message is shown after 3 seconds");
3
}
4

5
setTimeout(message, 3000);

setTimeout is a built-in function used to execute code after a specified period of time (in milliseconds). Here we’re telling setTimeout() to execute our message function (and log the contained message) after four seconds.


In this example, we defined the function with a name. However, you can also define a function as an “anonymous function”.


Callback as an Anonymous Function


Alternatively, we can define a function directly inside another function, instead of defining it someplace else and calling it. It will look like this: 















1
setTimeout(function() {  
2
    console.log("This message is shown after 3 seconds");
3
}, 4000);

In this case, the callback function is an anonymous function (a nameless function). The above code here runs exactly the same as the one in the previous section, but using an anonymous function makes the code more concise.


Callback as an ES6 Arrow Function


Arrow functions were introduced in JavaScript as part of the ECMAScript 2016 (ES6) specification. The arrow function syntax is currently supported by most major browsers and across versions.


We can write the same callback function as an arrow function: 















1
setTimeout(() => { 
2
    console.log("This message is shown after 3 seconds");
3
}, 3000);

The only difference between this and the anonymous function is that here we substitute the function keyword with the arrow symbol. The code runs just the same as those in the previous examples.


You can also refactor an arrow function into a one-liner if the content of the function is short: 





1
setTimeout(() => console.log("Just 3 seconds") , 3000);

Next up, Events.


What About Events?


In the previous example, we executed the callback after four seconds with setTimeout(). While this is a common use case for callbacks, it’s by no means the only one.


Callback functions are commonly used to respond to web page events such as clicking a button, hovering over an element, or submitting a form.


Consider the following button, for example:





1
<button id="callback-btn">Click here</button>

Let’s say we want to log a message when the user clicks on the button:



















1
document.queryselector("#callback-btn")
2
    .addEventListener("click", function() {    
3
      console.log("User has clicked on the button!");
4
});

First, we used the querySelector() method to select the button by its ID property. We then attach a “click” event listener to the element, passing in an anonymous callback function as the second parameter. Inside the function, we simply log a message on the console once the button is clicked.


Conclusion


To recap, a callback function is used to execute a set of instructions (code) after something else has happened. This “something else” could be an elapsed time or a page-related event, such as clicking a button.


Callbacks are used often in JavaScript, and I hope this post helps you understand what they actually do and how to work with them easier. To learn more about asynchronous code in JavaScript, read about JavaScript Promises.



Original Link: https://code.tutsplus.com/articles/how-to-use-callback-functions-in-javascript-es6--cms-106785

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code