Arrow Function is a new feature in Javascript that helps to write shorter and more readable code. Arrow Function provides a concise syntax for declaring functions and mapping parameters and function bodies.
Arrow Function is defined using the following syntax:
const functionName = (parameters) => {
// Phần thân hà m
};
In which:
If the function body has only one return statement, we can write it as follows:
const functionName = (parameters) => expression;
Here are some examples of using Arrow Function in Javascript:
Example 1: Function that returns the sum of two numbers
const addNumbers = (a, b) => a + b;
console.log(addNumbers(5, 3)); // 8
Example 2: Function to check if a number is even
const isEven = num => num % 2 === 0;
console.log(isEven(4)); // true
console.log(isEven(7)); // false
Example 3: Function to calculate the area of a rectangle
const calculateRectangleArea = (width, height) => width * height;
console.log(calculateRectangleArea(4, 5)); // 20
Example 4: Function to print a list of students to the screen
const students = ['John', 'Emily', 'David'];
const printStudents = () => {
students.forEach(student => {
console.log(student);
});
};
printStudents();
// John
// Emily
// David
Arrow Function brings some benefits when used in Javascript programming:
Although Arrow Function is very useful in many cases, there are also some points to note: