Reputation: 1360
I am maintaining some old code and I noticed that there are many instances where the old programmer left return;
statements as the final line in most of his functions. Is there any advantage to this? I feel like this is a waste of space, so I have been removing them as I see them. Is one of them generally faster?
Upvotes: 3
Views: 197
Reputation: 56034
From the ECMAScript Language Specification:
When the [[Call]] internal method for a Function object F is called with a this value and a list of arguments, the following steps are taken:
- Let funcCtx be the result of establishing a new execution context for function code using the value of F's [[FormalParameters]] internal property, the passed arguments List args, and the this value as described in 10.4.3.
- Let result be the result of evaluating the FunctionBody that is the value of F's [[Code]] internal property. If F does not have a [[Code]] internal property or if its value is an empty FunctionBody, then result is (normal, undefined, empty).
- Exit the execution context funcCtx, restoring the previous execution context.
- If result.type is throw then throw result.value.
- If result.type is return then return result.value.
- Otherwise result.type must be normal. Return undefined.
In other words, if the function that is called has no explicit return
statement, then it implicitly returns undefined
.
Upvotes: 2
Reputation: 69
The return statement is used to return a value from the function. You do not have to use a return statement; the program will return when it reaches the end of the function. If no return statement is executed in the function, or if the return statement has no expression, the function returns the value undefined.
return; //undefined
return
a+b;
// is transformed by ASI into
return;
a+b;
So you get undefined again.
Take a look at MDN documentation here
By the way, I found this link about performance and I've found a test that compares 4 expression, two function with a return and the same function without return.
Here you can see the test. Hope it is related with your question
Upvotes: 0