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.
const add = (a, b) => a + b;
console.log(add(5, 3));
Syntax:
const functionName = (parameters) => { // function body return result;};- const: declares the function as a constant variable.
- functionName: name of the arrow function.
- (parameters): inputs to the function.
- =>: arrow showing it’s an arrow function (replaces function keyword).
- { ... }: function body where code runs.
- return result; : explicitly returns a value.
1. Arrow Function without Parameters
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.
const gfg = () => {
console.log( "Hi from GeekforGeeks!" );
}
gfg();
2. Arrow Function with Single Parameters
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.
const square = x => x*x;
console.log(square(4));
3. Arrow Function with Multiple Parameters
Arrow functions with multiple parameters, like (param1, param2) => { }, simplify writing concise function expressions in JavaScript, useful for functions requiring more than one argument.
const gfg = ( x, y, z ) => {
console.log( x + y + z )
}
gfg( 10, 20, 30 );
4. Arrow Function with Default Parameters
Arrow functions support default parameters, allowing predefined values if no argument is passed, making JavaScript function definitions more flexible and concise.
const gfg = ( x, y, z = 30 ) => {
console.log( x + " " + y +