"Return"; necessary / useful when using callbacks in Node.JS?

For example, are these two effectively the same?

someFunction(val, callback){
    callback(val);
};

and

someFunction(val, callback){
    callback(val);
    return;  // necessary?
};
+5
source share
5 answers

Yes, they are the same. If your function does not return a value, you can either omit the return statement or use it without an argument; in both cases, calling the function returns "undefined".

function f1(){};
typeof(f1()); // => "undefined"

function f2(){return;};
typeof(f2()); // => "undefined"
+5
source

As long as they are the same, from time to time you will see something like the following:

someFunction(val, callback){
  if (typeof val != 'object')
    return callback(new Error('val must be an object'));
  callback(null, val);
};

, return "" . , ; ( , ), else.

+7

JavaScript , - , node.js .

someFunction() undefined. , .

+1

, var, . function ECMAscript implicity undefined, .

+1

; return, , .

sidenote: in some languages ​​(but probably not in javascript), the return statement may not even be executed if the tail calls optimization is enabled (that is, it is reasonable for the compiler to remove the function from the stack after it exits if you never plan to do that or else). Once again, it may not be relevant in any implementation of standard javascript.

0
source

All Articles