Tuesday, 3 December 2024

Arrow functions in Javascript

Arrow functions provide a shorter syntax for writing functions. They are always anonymous, and you can omit the function keyword.

arrowFunction.js

let add = (a, b) => {
	return a + b;
};

let a = 5;
let b = 3;
let sum = add(5, 3);

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output

Sum of 5 and 3 is 8

The code uses an arrow function, denoted by =>, which is a shorthand way to write a function expression in JavaScript.

 

If the function body contains only one expression, you can omit the curly braces and the return keyword.

let add = (a, b) => a + b;

arrowFunctionSingleExpression.js

let add = (a, b) => a + b;

let a = 5;
let b = 3;
let sum = add(5, 3);

console.log(`Sum of ${a} and ${b} is ${sum}`);

Output

Sum of 5 and 3 is 8

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment