When we think of the return
type, we think of the type of data, returned by the concerned function in JavaScript.
function welcome() { |
But, sometimes back came accross an example of a function.
function add(a, b) { |
What would be the output???
4 |
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 evaluates each of its operands (from left to right)
- The grouping operator () controls the precedence of evaluation in expressions.
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.