I'm trying out js2-mode, which is a kind of javascript IDE in emacs. One of the features is syntax error highlighting and style warnings. Since turning it on, I've noticed that I'm getting this one warning all over my code:
anonymous function does not always return a value
When I write a function whose responsibility is to call a callback, I often do not explicitly add a return value. Is that bad style?
For example:
function someFunc (requiredParam, callback) {
if (!requiredParam)
return callback("missing required param")
someAsyncMethod(requiredParam, function(someValue) {
callback(null, someValue)
})
}
where the return
only serves to ensure the rest of the function doesn't get executed. Is that better written as
function someFunc (requiredParam, callback) {
if (!requiredParam)
return callback("missing required param")
return someAsyncMethod(requiredParam, function(someValue) {
return callback(null, someValue)
})
}
The latter style is the only way to get js2-mode to leave me alone. Or maybe it should be written as
function someFunc (requiredParam, callback) {
if (!requiredParam) {
callback("missing required param")
} else {
someAsyncMethod(requiredParam, function(someValue) {
callback(null, someValue)
})
}
}
That also gives me a js2 pass, but I have always found the former style to read better. Am I doing it wrong or is js2-mode too uptight?
The consensus at work, and following from jfriend00, is that it should be written like this:
function someFunc (requiredParam, callback) {
if (!requiredParam) {
callback("missing required param")
return
}
someAsyncMethod(requiredParam, function(someValue) {
callback(null, someValue)
})
}
js2-mode was right. My desire to write one-liners was making my code less clear.