Compared to some functional languages, the function definition in JavaScript looks relatively clumsy:
const square = (x) => {
return x ** 2;
};
There are many extra characters and the word return. Since version ES6, a shorter syntax has appeared in the language. In some situations, this makes it make code much easier to understand and reduce the amount of it.
// It takes a little practice to get used to
// this form, but then you cannot live
// without it
const double = (x) => x ** 2;
There are two differences compared to the full definition: missing curly brackets and the return instruction.
The abbreviated function notation makes the return automatically. There is only one expression inside the function, which is calculated and returned as a value.
It is important to emphasize that the differences are purely syntactic; there are no differences in terms of usage. Let's explore an example with two arguments.
The full version is:
const sum = (a, b) => {
return a + b;
};
The shortened version is:
const sum = (a, b) => a + b;
Notice the absence of curly brackets. Some developers sometimes write code like this const sum = (a, b) => { a + b }; and then cannot understand why it doesn't work.
The answer is quite straightforward: if there are curly brackets, then it is not a short form. It means that you should add return to get the function to return a value.