Adam es correcto; Ambas funciones devuelven indefinido, y de cualquier forma es absolutamente correcto si no te importa el valor de retorno (o deseas que el valor no esté definido). Sin embargo, a menudo es mejor en programas más complejos para regresar explícitamente de una función, especialmente porque los programas de Javascript a menudo tienen mecanismos de devolución de llamada complejos. Por ejemplo, en este fragmento de código (sólo un poco más complejo que el suyo) Creo que la instrucción de retorno realmente ayuda a clarificar el código:
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();
Una buena respuesta a esto debe incluir un enlace a la parte pertinente de la ECMA especulación. – georg
devolución; básicamente significa terminar la función aquí. Entonces, si lo tienes como el último trozo de tu función, no hace nada útil. – gintas
12.9 en la especificación, para aquellos interesados. – davin