![]() |
VOOZH | about |
Arrow functions in JavaScript are a concise way to write functions using the => syntax, automatically binding this from the surrounding context.
The following code defines an arrow function that takes two numbers and returns their sum.
Syntax:
const functionName = (parameters) => { // function body return result;};An arrow function without parameters is defined using empty parentheses (). This type of function is useful when no input values are needed, such as for callbacks, timers, or simple operations.
When an arrow function has only one parameter, parentheses around the parameter can be omitted, making the syntax shorter and cleaner. This is commonly used in callbacks, array methods, or simple operations.
Arrow functions with multiple parameters, like (param1, param2) => { }, simplify writing concise function expressions in JavaScript, useful for functions requiring more than one argument.
Arrow functions support default parameters, allowing predefined values if no argument is passed, making JavaScript function definitions more flexible and concise.
In JavaScript, returning object literals within functions is concise: () => ({ key: value }) returns an object { key: value }, useful for immediate object creation and returning.
Arrow functions become asynchronous by adding the async keyword.
Here is the detailed Comparison between Arrow Functions and Regular Functions:
| Arrow Functions | Regular Functions |
| Lexically binds this to the surrounding context | this is dynamically bound depending on how the function is called |
| Shorter and more concise | Requires the function keyword |
Does not have its own arguments object | Has its own arguments object |
| Cannot be used as a constructor | Can be used as a constructor with new |
| Cannot be used as methods within objects | Can be used to define methods in objects |
| Implicit return for single expressions | Must use return keyword |