Arrow Functions
Arrow functions allow you to write functions more concisely.
Arrow functions are created using the arrow (=>
) symbol instead of the function
keyword.
Basic Structure of Arrow Functions
const functionName = (parameter1, parameter2) => {
// function body
};
Example of an Arrow Function
const add = (a, b) => a + b;
console.log(add(1, 2)); // Outputs 3
Using arrow functions can make your code simpler compared to traditional function expressions.
Comparison of Traditional and Arrow Functions
// Traditional function
const sayHello = function (name) {
return 'Hello, ' + name + '!';
};
// Arrow function
const sayHello = (name) => 'Hello, ' + name + '!';
Examples of Arrow Functions
Here are some examples of how you can use arrow functions.
When There Are No Parameters
You can use empty parentheses to indicate no parameters.
Arrow Function with No Parameters
const greet = () => 'Hello!';
When There Is One Parameter
Parentheses can be omitted when there is a single parameter.
Arrow Function with One Parameter
const double = x => x * 2;
When There Are Two or More Parameters
List parameters separated by commas.
Arrow Function with 2 or More Parameters
const add = (a, b) => a + b;
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.