Search⌘ K

Functions, Arrow Functions, and Callbacks

Explore how regular functions, arrow functions, and callback functions work in JavaScript. Learn their differences, uses, and how callbacks handle asynchronous tasks and array methods to improve React coding efficiency.

Functions are instrumental in JavaScript programming and an essential concept for React development. Functions are blocks of reusable code that perform a specific task. They're necessary to write more concise and readable code, especially when creating React components.

JavaScript offers three primary types of functions:

  • Regular functions

  • Arrow functions

  • Callback (async) functions

Regular functions (standard functions)

In JavaScript, regular functions are declared using the function keyword. They can take parameters, perform operations, and return values.

Javascript (babel-node-es2024)
console.log(greet("Alice")); // Hello, Alice!
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
// An anonymous function assigned to a function expression
const add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // 5
// Anonymous function (without a name)
setTimeout(function() {
console.log("This runs after 2 seconds");
}, 2000);

Note:

  • Function declarations are hoisted, so they can be called before they are defined, e.g., greet function can be called before its definition.

  • Function expressions ...