Unless you have a specific reason for ending the function early, a single return right at the end of the function is generally the best place to put it.
Most JavaScript functions are relatively simple. Many will only have a return statement and determine the value in that one line.
If your function contains more than a couple of dozen lines then you are probably trying to do too much. Even polyfills to add the new commands to older browsers are seldom longer than that.
As an example - here’s one I wrote earlier today that processes all the elements in an array and converts them all to lowercase.
Array.prototype.toLowerCase= function(){
return this.map(function(a) {return (a.toLowerCase)?a.toLowerCase():a;});
};
Here’s a more complicated one that examines all of the parameters passed to it and works out the mode (the entry or entries that occur most frequently) and returns those entries.
var getMode = function() {
var ary, i, max, mode, str;
ary = Array.prototype.slice.call(arguments);
max = 0;
mode = [];
str = ary.sort();
str = "~" + str.join('~~') + "~"
str.replace( /(~\-?\d+~)\1*/g, function(a,b){
var m = a.length / b.length;
if (max <= m ) {
if (max < m) {mode = [];max = m;}
mode.push( +b.replace(/~/g,""));
}
});
return mode;
}
As you can see, each has a single return statement at the end.
In some rare cases where the function can return completely different types of results you might have more than one return. Probably the most common situation where this happens is where you are returning true or false - for example this polyfill for the array every() method:
if (!Array.prototype.every) {
Array.prototype.every = function(fun) {
"use strict";
var t, len, thisp, i;
if (this == null)
throw new TypeError();
t = Object(this);
len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
thisp = arguments[1];
for (i = 0; i < len; i++) {
if (i in t && !fun.call(thisp, t[i], i, t))
return false;
}
return true;
};
}