Is there any difference between a function with and without a return statement?

Say you have two identical functions that do not return a value

function a() { // do some interesting things } function b() { // do the same interesting things return; } 

Function b is obviously more verbose, but is there any functional difference between these?

+6
source share
3 answers

There is no real difference; both will return undefined .

Functions without a return statement return undefined , as it would with an empty return .


To confirm this, you can run this code - FIDDLE :

 function a() { } function b() { return; } var aResult = a(); var bResult = b(); alert(aResult === bResult); //alerts true 
+10
source

Adam is right; both functions return undefined, and in any case, it is absolutely normal if you do not care about the return value (or want the value to be undefined). However, often in more complex programs there is often an explicit return from a function, especially since Javascript programs often have complex callback mechanisms. For example, in this piece of code (a little more complicated than yours), I believe that the return statement really helps clarify the code:

 function someAsyncFunction(someVar, callback) { // do something, and then... callback(someVar); // will return undefined return; } function c(){ var someState = null; if (some condition) { return someAsyncFunction(some variable, function () { return "from the callback but not the function"; }); // we've passed the thread of execution to someAsyncFunction // and explicitly returned from function c. If this line // contained code, it would not be executed. } else if (some other condition) { someState = "some other condition satisfied"; } else { someState = "no condition satisfied"; } // Note that if you didn't return explicitly after calling // someAsyncFunction you would end up calling doSomethingWith(null) // here. There are obviously ways you could avoid this problem by // structuring your code differently, but explicit returns really help // avoid silly mistakes like this which can creep into complex programs. doSomethingWith(someState); return; } // Note that we don't care about the return value. c(); 
+3
source

Typically, you return a value. For example,

 function b() { return 'hello'; } a = b(); console.log(a); 

Will output "hello" to your console.

+1
source

Source: https://habr.com/ru/post/909293/


All Articles