↘️ Arrow Function in Action
Arrow Functions provide a shorter syntax for writing functions. Instead of using the function keyword, you use an arrow (=>).
Arrow functions are written with the => symbol, which makes them compact.
For functions with a single expression, the return is implicit, making the code more concise.
Like any variable, an arrow function can be declared using const, var or let. However it is a best practice to use const with arrow function unless we have a strong reason to reassign them,
Example: Below is the example that illustrates the use of the Arrow Function.
let add = (a, b) => a + b;
console.log(add(3, 2)); //5'add' is an arrow function that takes two parameters a and b, and returns their sum.
➡️ Arrow Function without Parameters
An arrow function without parameters is defined using empty parentheses (). This is useful when you need a function that doesn’t require any arguments.
Example :
const gfg = () => {
console.log( "Hi from Codeveda!" );
}
gfg();Hi From Codeveda!Explanation:
gfgis an arrow function with no parameters.It prints a message to the console when called.
gfg();is the function call that triggers the message.
✔️ Arrow Function with Single Parameters
If your arrow function has a single parameter, you can omit the parentheses around it.
Example :
const square = x => x*x;
console.log(square(4)); //16Explanation:
squareis an arrow function that takes one parameterx.It returns the result of
x * x(i.e., the square ofx).square(4)returns16, which is printed usingconsole.log.
Since it's a single-line function, the return is implicit — no need to write return or use {}.
▶️ 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.
Example :
const gfg = ( x, y, z ) => {
console.log( x + y + z )
}
gfg( 10, 20, 30 ); //60Explanation:
gfgis an arrow function that takes three parameters:x,y, andz.Inside the function, it calculates the sum of
x,y, andz.gfg(10, 20, 30)calls the function with10,20, and30, which adds up to60.
🏷️ 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.
Example :
const gfg = ( x, y, z = 30 ) => {
console.log( x + " " + y + " " + z);
}
gfg( 10, 20 ); //10 20 30Explanation:
z = 30means: If the caller doesn't provide a third argument,zwill default to30.gfg(10, 20)provides values forxandy, but notz, so it uses the default.The function logs the three values as a space-separated string:
10 20 30.
🧩 Benefits:
Makes function calls more flexible.
Helps avoid
undefinedvalues when optional parameters are skipped.Great for creating fallback values in functions.