Introduction
Arrow functions introduced in ES6 is a concise way of creating functions compared to function expressions.
The name arrow function comes from the use of =>
.
Syntax:
const functionName = (arg1, arg2, ... argN) => {
return value;
}
Example
const multiply = (a, b) => {
return a * b;
}
console.log(multiply(7, 8)); // 56
console.log(multiply(3, 2)); // 6
Key Features
- Arrow functions are anonymous function until they are assigned to a variable.
- If there is only 1 argument, we can skip parenthesis.
const square = x => {
return x * x;
}
console.log(square(2)); // 4
console.log(square(7)); // 49
The only caveat to this rule is that if the 1 argument is destructured.
const foo = ({name = "New User"}) => name;
console.log(foo({})); // New User
console.log(foo({name: "Parwinder"})); // Parwinder
- If there are no arguments, we need to have the parenthesis
const greeting = () => {
return "Hello World!";
}
console.log(greeting()); // Hello World!
- If the function body is an expression, it will return the expression, we can remove the brackets and the return keyword.
const greeting = () => "Hello World!";
console.log(greeting()); // Hello World
Now that we know all these key features, let us rewrite the example to get the square of a number:
const square = x => x * x;
console.log(square(4)); // 16
Top comments (7)
Unless there's one argument which is destructured.
Rather, if the function body is an expression, the value of the expression is returned.
Consider why the following is not legal -- it is one statement, but it is not a valid expression.
This is also why you need parentheses in the following case
I do consider both examples as edge cases but they are correct and valid. I have updated the article to showcase them. I appreciate the feedback.
Thanks for reading! ♥️
"Hello World!" is not a statement, and if it were, it would not return.
It is an expression, and it evaluates.
Yep agreed. Corrected the post as I mentioned above.
Looking better, although
If it has {} or return, then the function body isn't an expression. :)
I think the simplest way to express it is that there are two distinct forms.
Your bullet point 2 is generally how folks write functions if they are not using shorthand. That is why my blog post starts with the example of an arrow function that has {} and return.
The shorthand is omitting the braces and return when there is one expression, Which is reflected by the fourth bullet point (or the part you just quoted). So at this point I am covering both the points you mentioned.
Thanks for the feedback.
Sure. The main thing is not to conflate expressions and statements. :)