Define One-Line Arrow Function

So, this code works:

console.clear();

const howMany = (...args) => { return "You have passed " + args.length + " arguments.";
}
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.

This code doesn’t:

console.clear();

const howMany = (...args) => {  "You have passed " + args.length + " arguments.";}

console.log(howMany(0, 1, 2)); // undefined

console.log(howMany("string", null, [1, 2, 3], { })); //  undefined

I would have expected that the second example is still a one-line arrow function, and the “return” keyword could be omitted. It can’t, so, should I conclude that because of the use of Javascript string literals it is no longer considered to be a one-line function?

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

if you have graph parenthesis, the body of the function has nothing implicit, and you need to explicitly use the return keyword

for implicit return you need to remove the graph parenthesis

x => x
// same as
x => { return x; }
1 Like