Arrow functions are a concise way to write functions in javaScript. They were introduced in ECMAScript 6 (ES6) and provide a shorter syntax compared to traditional function expression.
Arrow functions are particularly useful for writing small, anonymous functions, especially when you need to use them a callbacks or for simple one-liner functions.
Syantx
const functionName = (parameters) => {
// Function body
return result;
};
const functionName: You can assign the arrow function to a variable, and you can give it a name (optional).(parameters): This is a list of parameters that the function takes, just like in a regular function.=>: This is the arrow operator, which signifies that you’re declaring an arrow function.{}: These curly braces contain the function body. If the function body consists of a single expression, you can omit the curly braces and thereturnkeyword.return result: If the function has a single expression, you can directly return the result without using thereturnkeyword. This is called an implicit return.
- a basic arrow function without parameters:
const greet = () => {
return "Namaste, World!";
};
console.log(greet()); // Outputs: Namaste, World!
2. An arrow function with parameters:
const add = (a, b) => {
return a + b;
}
console.lgo(add(5, 3)); //Outputs: 8