arrow function in javascript

Arrow functions are a syntactically shorter way to write function expressions in JavaScript. They are commonly used in ES6 and onwards.

Below is the code syntax for an arrow function:

index.tsx
(parameter1, parameter2, ...) => { 
   // Function Body 
}
59 chars
4 lines

Here is an example of an arrow function that adds two numbers:

index.tsx
const addNumbers = (a, b) => {
   return a + b;
}

console.log(addNumbers(5, 10)); // Output: 15
97 chars
6 lines

In this example, addNumbers is the name of the arrow function we defined. We passed in two parameters, a and b, and returned their sum using the return statement.

Note that if the function simply returns a value and nothing else, the code can be shortened even further:

index.tsx
const addNumbers = (a, b) => a + b;

console.log(addNumbers(5, 10)); // Output: 15
83 chars
4 lines

This code has the same output as the previous example, but the function declaration is shorter because it omits braces and the return statement.

gistlibby LogSnag