What would happen if we didn’t omit the return keyword

If an arrow function had one task to perform (E.g. add two inputs together), we could omit the curly braces and the return keyword

const add = (num1, num2) => num1 + num2

console.log(add(5, 10)); // 15

However, I was wondering what would happen if we didn’t omit the return keyword

const add = (num1, num2) => return num1 + num2; // Uncaught SyntaxError: expected expression, got keyword 'return'

It threw an error saying that it expected an expression. However, what I don’t understand is that we could’ve written a log statement, which is not an expression without getting an error

const add = (num1, num2) => console.log(num1 + num2);

add(5, 10); // 15

How does this work?

Return can only be used in a function body. A concise arrow function has no body for a single expression, and it has an implicit return. Once we add the return keyword it is no longer an expression, but a statement so must be contained in curly braces. console.log() is actually an expression, which is why it works, above.


I thought expression resulted in a single value:

2 + 5 = 7
5 = 5
1 - 6 = 5

And statements were actions that the computer perfoms:

console.log("test"); // The computer will log "test" to the console
if (condition) {statements} // The computer is checking for a conditon and will perform actions depending on the condition

How is console.log() an expression?

It does result in a single value, the string expression it logs to the console. Anything that can be returned is an expression since we cannot return a statement from a function.

foo = function (bar) {
    return console.log(bar)

foo ('foobar')    //  foobar
1 Like

Ok, thank you!

Out of curiosity, when I tested your code snippet in the Firefox Developer Console, the output was image

Can you explain this output please including undefined?

The output is what was logged, and the undefined is what was returned from console.log(), and hence returned from the function. Normally we wouldn’t write it this way, but we’ve shown above that we can still do it.

1 Like

Ok, so even though we returned console.log(bar), the log method still gets invoked as we appended the method name with parenthesis. Because the log method returns undefined, the function will return undefined

foobar => console.log() output
undefined => function return value
1 Like

@mtf One last question

So why does it return undefined and not the string expression between its parenthesis

This is like saying, 2 evaluates to 2 but it returns undefined. console.log("Hello") evaluates to "Hello" but it returns undefined?

As you mentioned above, the method is invoked before the return, but it does not return the value, only logs it. console.log() itself has no return.

1 Like

which means that it returns undefined

1 Like