EN
JavaScript - arrow functions
0 points
In this article, we would like to show you how to create and use arrow functions in JavaScript.
Quick solution:
xxxxxxxxxx
1
const functionName = () => {
2
// function body here
3
};
with arguments:
xxxxxxxxxx
1
const functionName = (arg1, arg2) => {
2
// function body here
3
};
without parentheses:
xxxxxxxxxx
1
const multiply = x => x * 2; // example function that multiplies by 2
In this example, we create a simple arrow function with no arguments.
xxxxxxxxxx
1
const helloWorld = () => {
2
console.log('Hello World!');
3
}
4
5
helloWorld(); // Hello World!
In this example, we create a simple arrow function that displays its arguments in the console.
xxxxxxxxxx
1
const display = (x, y) => {
2
console.log('Argument1 = ' + x);
3
console.log('Argument2 = ' + y);
4
}
5
6
display(1, 2);
7
display('a', 'b');
Output:
xxxxxxxxxx
1
Argument1 = 1
2
Argument2 = 2
3
Argument1 = a
4
Argument2 = b
In this example, we create an arrow function with no parentheses. The function multiplies the given number by 2
. Notice that in this kind of function you don't need the return
statement.
xxxxxxxxxx
1
const multiply = x => x * 2;
2
3
4
// usage example
5
6
const result1 = multiply(1);
7
const result2 = multiply(2);
8
9
console.log(result1); // 2
10
console.log(result2); // 4
In this example, we present a comparison of the arrow function with a normal function.
Arrow function solution:
xxxxxxxxxx
1
const multiply = x => x * 2;
2
3
// usage example
4
const result = multiply(1);
5
console.log(result); // 2
is equal to:
xxxxxxxxxx
1
const multiply = function (x) {
2
return x * 2;
3
}
4
5
// usage example
6
const result = multiply(1);
7
console.log(result); // 2