Arrow Functions
Arrow functions allow you to represent functions more concisely.
Instead of using the function
keyword, arrow functions use the arrow symbol (=>
) to define functions.
Basic Structure of Arrow Functions
const functionName = (parameter1, parameter2) => {
// function content
};
Example of Arrow Function
const add = (a, b) => a + b;
console.log(add(1, 2)); // Outputs: 3
Advantages of Arrow Functions
- You can write your code more concisely compared to traditional functions.
Comparing Traditional Functions and Arrow Functions
// Traditional function
const sayHello = function (name) {
return 'Hello, ' + name + '!';
};
// Arrow function
const sayHello = (name) => 'Hello, ' + name + '!';
Examples of Arrow Functions
Without Parameters: You can omit the parentheses if there are no parameters.
Arrow Function with No Parameters
const greet = () => 'Hello!';
With One Parameter: You can omit the parentheses.
Arrow Function with One Parameter
const double = x => x * 2;
With Two or More Parameters: You must use the parentheses.
Arrow Function with Two or More Parameters
const add = (a, b) => a + b;
With Multiple Lines of Code in the Function Body: Use curly braces ({ }
) and explicitly state the return
keyword if you need to return a value.
Arrow Function with Multiple Lines of Code
const getMax = (a, b) => {
if (a > b) {
return a;
} else {
return b;
}
};
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.