What is the difference between explicitly specifying a return statement in JS and not having a return statement?

I am maintaining some old code and I noticed that there are many cases where an old programmer left expressions return;

as the last line in most of his functions. Are there any benefits for this? I feel like they are a waste of space, so I delete them as I see them. Is one of them usually faster?

+3


source to share


2 answers


From the ECMAScript Language Specification :

When the [[Call]] internal method for a function object F with this value and a list of arguments, the following steps are: Suggested solution:

  • Let funcCtx be the result of creating a new execution context for the function code using the value of the F [[FormalParameters]] internal property, the arguments passed is a list of args and this value is as described in 10.4.3 .
  • Let the result be the result of evaluating FunctionBody, which is the value of the internal property F [[Code]]. If F has no [[Code]] internal property, or if its value is an empty FunctionBody, then the result is (normal, undefined, empty).
  • Close the funcCtx execution context by restoring the previous execution context.
  • If result.type is throw, then throw result.value.
  • If result.type is a return, then we return result.value.
  • Otherwise, result.type should be normal. Return undefined .


In other words, if the called function has no explicit expression return

, then it implicitly returns undefined

.

+2


source


The return statement is used to return a value from a function. You don't need to use the return statement; the program will return when it reaches the end of the function. If the function does not execute a return statement, or if the return statement has no expression, the function returns undefined .

return; //undefined


return
a+b; 
// is transformed by ASI into
return;
a+b;

      

So you get undefined again.



Take a look at the MDN documentation here

BTW, I found this performance link and I found a test that compares 4 expressions, two functions with a return and the same function without a return.

Here you can see the test. Hope this is related to your question.

0


source







All Articles