JavaScript: What is the type of 'return'

Apr 20, 2016

When we think of the return type, we think of the type of data, returned by the concerned function in JavaScript.

function welcome() {
return "Welcome!!!"; /// Return type is 'String'

But, sometimes back came accross an example of a function.

function add(a, b) {
return (
console.log(a + b),
a + b

console.log(add(2, 2));

What would be the output???

[2, 2]

Amazing. Right. Or you’re not amazed, buffled, taken-aback, surprised as I was. May be you know why this is happenning. May be you know about grouping operator, comma operator or you may have already read the ECMA specification for return and function. If neither any of these is your case, read on.

I posted one question in StackOverflow regarding this. Many programmers answered and participated in the discussion. Actually if all of the concepts liknked in the above para is clear to one, there should not arise any question. But, it’s me. Never read properly. :P

The question was, is return here is behaving like a function, as we are kind of passing arguments into it.

Answer: No

If we try to print the typeof return it gives SyntaxError: Unexpected token return. As return is a statement by specification and typeof expects identifier after it, JavaScript engine won’t evaluate the expression. So, what happens here.

The comma operator makes the evaluation of each of the expressions passed to the grouping opeartor. So, we get the first two lines of the output.

And the grouping operator is responsible to return the evaluated value of the last expression, separated by comma.

Quite simple. Right.

Blog comments powered by Disqus