Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "return;" necessary/helpful 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?
};
like image 284
randylubin Avatar asked Feb 29 '12 23:02

randylubin


2 Answers

While they are the same, you will see something like the following from time to time:

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

In other words, return is used to "break" out of the function early. Most often, I've seen that used with conditionals; you test for an error condition (returning the callback early if there is an error), then avoid having to wrap the remainder of the function in an else clause.

like image 109
danmactough Avatar answered Sep 22 '22 13:09

danmactough


Yes, they are the same. If your function does not return a value then you can either omit the return statement or use it with no argument; in both cases a call to the function returns "undefined".

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

function f2(){return;};
typeof(f2()); // => "undefined"
like image 24
maerics Avatar answered Sep 24 '22 13:09

maerics