Empty Functions In Javascript
Solution 1:
I don't know what jsLint
thinks but if this is a problem and you need a solution then you can do something like the following:
var blah = function() { returnundefined; }; // or just return;
Update : I think, Bergi
's guess is right because, on the jslint site in the Required Blocks
section :
JSLint expects that if, while, do and for statements will be made with blocks {that is, with statements enclosed in braces}.JavaScript allows an if to be written like this:if (condition) statement;That form is known to contribute to mistakes in projects where many programmers are working on the same code. That is why JSLint expects the use of a block:
if (condition) { statements; }
Experience shows that this form is more resilient.
So, It probably just checks for empty blocks { }
and invalidate the blank function.
Solution 2:
Use the lambda expression:
constblah = () => void0;
This will make it clear that blah
is an empty function that returns undefined
.
Solution 3:
If you are asking what JsLint option turns this warning off it is: "debug:true"
Strangely, the docs make no reference to this behavior:
"Tolerate debugger statements" | debug | true if debugger statements should be allowed. Set this option to false before going into production.
But if you look at the code, you can see that it won't warn you with the debug option set to true:
functionblock(kind) {
// A block is a sequence of statements wrapped in braces.
...
if (kind !== 'catch' && array.length === 0 && !option.debug) {
curly.warn('empty_block');
}
...
}
Solution 4:
A lot of code checkers check for this sort of thing. It doesn't mean you should never have empty code blocks. Sometimes there are valid reasons for having them. But it often means that the programmer just forgot to write the implementation. :)
What I like to do is put a comment in the function body, explaining why it's empty. This should suppress the warning, but it may not depending on whether the code checker considers a code block with a comment "empty".
var blah = function() { /* empty because ... */ };
Solution 5:
If you intend to use the function as a constructor with the new
operator:
// Returns the instance that was just created with the new operator.varClassLikeFunction = function(){
returnthis;
};
On the other hand, if is intentionally a blank function with no return value:
// Returns the same value as a function that returned nothing.var blankFunction = function(){
returnundefined;
};
Post a Comment for "Empty Functions In Javascript"