Empty functions in Javascript - javascript

If I have something like this:
var blah = function() { };
and then later in code blah is being used, what is the JSLint hint that says remove the empty block?

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() { return undefined; }; // 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.

Use the lambda expression:
const blah = () => void 0;
This will make it clear that blah is an empty function that returns undefined.

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:
function block(kind) {
// A block is a sequence of statements wrapped in braces.
...
if (kind !== 'catch' && array.length === 0 && !option.debug) {
curly.warn('empty_block');
}
...
}

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 ... */ };

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.
var ClassLikeFunction = function(){
return this;
};
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(){
return undefined;
};

This
{
...
}
is considered a code block and the hint is letting you know that it is empty (there are no commands in it). You don't have to remove it though, as #Katana314 said, it could be intentional.

what let me to this question is that I had an empty function in my namespace
and when I called that function, and
TypeError: MyNamespcae.myFunction is not a function
so don't create an empty function, at lease add one statement like void(0); or return null;

Related

Return statement in `finally` overrides return statement in `try` [duplicate]

How does a return statement inside a try/catch block work?
function example() {
try {
return true;
}
finally {
return false;
}
}
I'm expecting the output of this function to be true, but instead it is false!
Finally always executes. That's what it's for, which means its return value gets used in your case.
You'll want to change your code so it's more like this:
function example() {
var returnState = false; // initialization value is really up to the design
try {
returnState = true;
}
catch {
returnState = false;
}
finally {
return returnState;
}
}
Generally speaking you never want to have more than one return statement in a function, things like this are why.
According to ECMA-262 (5ed, December 2009), in pp. 96:
The production TryStatement : try Block Finally is evaluated as follows:
Let B be the result of evaluating Block.
Let F be the result of evaluating Finally.
If F.type is normal, return B.
Return F.
And from pp. 36:
The Completion type is used to explain the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control. Values of the Completion type are triples of the form (type, value, target), where type is one of normal, break, continue, return, or throw, value is any ECMAScript language value or empty, and target is any ECMAScript identifier or empty.
It's clear that return false would set completion type of finally as return, which cause try ... finally to do 4. Return F.
When you use finally, any code within that block fires before the method exits. Because you're using a return in the finally block, it calls return false and overrides the previous return true in the try block.
(Terminology might not be quite right.)
The finally block rewrites try block return (figuratively speaking).
Just wanted to point out, that if you return something from finally, then it will be returned from the function. But if in finally there is no 'return' word - it will be returned the value from try block;
function example() {
try {
return true;
}
finally {
console.log('finally')
}
}
console.log(example());
// -> finally
// -> true
So -finally- return rewrites the return of -try- return.
I'm gonna give a slightly different answer here: Yes, both the try and finally block get executed, and finally takes precedence over the actual "return" value for a function. However, these return values aren't always used in your code.
Here's why:
The example below will use res.send() from Express.js, which creates a HTTP response and dispatches it.
Your try and finally block will both execute this function like so:
try {
// Get DB records etc.
return res.send('try');
} catch(e) {
// log errors
} finally {
return res.send('finally');
}
This code will show the string try in your browser. ALSO, the example will show an error in your console. The res.send() function is called twice. This will happen with anything that is a function. The try-catch-finally block will obfuscate this fact to the untrained eye, because (personally) I only associate return values with function-scopes.
Imho your best bet is to never use return inside a finally block. It will overcomplicate your code and potentially mask errors.
In fact, there's a default code inspection rule set-up in PHPStorm that gives a "Warning" for this:
https://www.jetbrains.com/help/phpstorm/javascript-and-typescript-return-inside-finally-block.html
So what do you use finally for?
I would use finally only to clean-up stuff. Anything that is not critical for the return value of a function.
It may make sense if you think about it, because when you depend on a line of code under finally, you are assuming that there could be errors in try or catch. But those last 2 are the actual building blocks of error handling. Just use a return in try and catch instead.
why you are getting false is you returned in a finally block. finally block should execute always. so your return true changes to return false
function example() {
try {
return true;
}
catch {
return false;
}
}
Returning from a finally-block
If the finally-block returns a value, this value becomes the return
value of the entire try-catch-finally statement, regardless of any
return statements in the try and catch-blocks
Reference: developer.mozilla.org
As far as I know, the finally block always executes, irrespective of whether you have a return statement inside try or not. Ergo, you get the value returned by the return statement inside finally block.
I tested this with Firefox 3.6.10 and Chrome 6.0.472.63 both in Ubuntu. It is possible that this code may behave differently in other browsers.
Finally is supposed to ALWAYS run at the end of a try catch block so that (by specification) is why you are getting false returned. Keep in mind that it is entirely possible that different browsers have different implementations.

Javascript syntax - If statements and Function calls

I have a syntax question, lets say i have the following function. It received text for spell check and returns the correct text or false in case the text was already spelled correctly.
var spellCheck = function (txt) {
var spelledTxt = spell(txt);
if (spelledTxt =! txt) { //the text had a typo.
return spelledTxt;
}
return false;
}
Now in a different function i want to call this function from an ElseIf statement, and i want to get into that statement only if the text had a typo which was corrected. something like:
if(something){
do something....
}else if(spellCheck(word)){
do something with the spelledTxt that was returned from "spellcheck"
}
Can i just do:
else if(var spelledWord = spellCheck(word))
do something with spelledWord.
I forgot a very important thing: spellCheck(word) is very heavy function and i'd like to avoid calling it if not needed. This mean that only if we arrived to the else if() it will be called, and not sooner.
Any expression is valid inside an if statement, and that includes an assignment expression. The value of an assignment expression is the assigned value.
In your case the return value of the function call is the value of the expression, but the var makes it a statement and not a simple expression.
You need to remove the variable declaration part from the statement and then it's fine.
Alternatively, you could simply do it like this:
else {
var spelledWord = spellCheck(word);
if(spelledWord)
do something with spelledWord
}
You can do that. The assignment operation returns a value, which you could use as a boolean expression.
But you should remember that:
In Javascript var statement is function-scoped.
There is a 'hoist' behavior in Javascript.
As a result of 1,2 and some later code refactoring, you could easily introduce a bug to this code.
Type coercion in Javascript is a bit messy.
Reading code with side effects, where one operation could lead to 2 different logic outcomes simultaneously - is really hard work.
I'd consider using the strict comparison operators at least: if (spelledWord = spellCheck(word) !== '')
And if it's possible, try to memoize (cache) results from calling spellCheck function. In that case, you wouldn't need to combine two operations into one at all.

Strange javascript code

I have found this code snippet:
;
100% function($) { // WTF?
var _true_ = true; // WTF?
var _false_ = false; // WTF?
var go = function(location, date) {
location || (location = {});
var result = _false_;
if (date && date.day) {
result = geoService.go(location, date);
}
return !!result;
}
var process = function(func) {
var args = [].prototype.slice.call(arguments, 1);
return function() {
return func.apply(this, args);
}
}
// ...
}(jQuery, undefined);
In here: http://www.dofactory.com/products/javascript-jquery-design-pattern-framework
(sorry, no id-s have been found on the page)
I don't understand what these parts are doing:
the "100%" in the second line
the var _true_ = true; and var _false_ = false; assignments in the 3-4 lines
I'm curious, what is the purpose of these.
the "100%" in the second line
It's the number 100 followed by a modulus operator. It's not used for anything (since the result isn't captured) other than to force the right hand side to be treated as a function expression instead of a function declaration.
It's a very uncommon and unintuitive approach that I've never seen before.
It is more usual to wrap the function expression in parens or precede it with a not operator.
the var true = true; and var false = false; assignments in the 3-4 lines
The author appears to be trying to draw attention to the uses of true and false by copying them to variables that include non-alpha numerica characters in the name instead of using literals throughout. Again, this is very odd and not something I've ever seen before.
It looks like it is a collection of wrongly used "best practices" which not led to exceptions but definitely odd and obscured. Look at second and last lines. There is best practice used exactly vice versa:
(function ($, undefined){
// do the stuff
})(jQuery);
undefined here will be the real undefined because when function call there is no second argument. But what on Earth can be the reason pass the "undefined" argument to the function and do not use it? It looks like a prank.
The same thing is on 5 line: it looks (and actually acts) as "default argument" assigning but done in strange manner (traditionally and more obviously it used as location = location || {};). I beleive that only reasons to write it that way it done can be obfuscation, joke or misunderstanding.
The same thing is with 100%. You can use any operators to indicate function expression. The most common way is to use parenthesis. But often you can also meet:
!function(){
}();
or:
+function(){
}();
but you can also write
42 * function(){
}();
it all acts the same way only parenthesis are most obvious and common.

Javascript alert never fires

Here is my code in its entirety:
if( javascript.isGarbage() != true) {
alert('I am not garbage!');
}
Why does this not alert anything???
If that is your code in its entirety, then javsacript is not defined. This will throw an error when you try .isGarbage() on it. Also, the string you pass to alert is missing its closing quote, as Firas pointed out (I missed this at first!).
It's possible to correct this code one of two ways. You can make javsacript an empty object, and then it will no longer error.
var javsacript = {};
if (javsacript.isGarbage() != true) {
alert('I am not garbage!');
}
Alternatively, you can add an additional check to make sure javsacript is truthy, i.e. defined as an object or some other value that will prevent an error when calling isGarbage() on it.
if (javsacript && javsacript.isGarbage() != true) {
alert('I am not garbage!');
}
Note: I'm not sure if "javsacript" is supposed to be "javascript." Ultimately it does not matter since neither one have been defined.
jav-"sa"-cript isn't a real word. Does your code rely on "javascript" being properly spelled? Is that really your whole code, or is "javsascript" part of some library?
You'll have to declare var javsacript = somevalue somewhere first before it can be used in any meaningful way.

JavaScript coding technique or bad code?

While debugging javascript written by someone else, I came across some code that I've not seen before. Here's a sample:
function doSomething() {
//doing something here...
}
function doItNow() {
//other logic...
doSomething && doSomething(); // <=== What's this?
}
Is the purpose of the 2nd line in function doItNow() to check if doSomething exists and then call it? Like so:
function doItNow() {
//other logic...
if (doSomething) {
doSomething();
}
}
JSLint does not like it and I'd rather not have bad code in my app. Any insights?
It's a 'shorthand' indeed. The right side is only executed when the left side passes as if() statement.
Google Closure Compiler and other minifiers take advantage of this; if your input is if(a) a(), it will result in a&&a()
You could do the same with ||, for example:
if( !a ){
alert('Not a');
}
can be written as
a || alert('Not a');
Yes, your two examples are "equivalent", the && operator performs short-circuit evaluation.
If the first operand expression yields a falsey value (such as null, undefined, 0, NaN, an empty string, and of course false), the second operand expression will not be evaluated, and if the value is truthy, the function call will be made.
But if doSomething hasn't been declared, your both examples will fail.
If an identifier that's not declared, is referenced on code, you will get a ReferenceError exception, e.g.:
function foo() {
undeclared && undeclared();
}
try {
foo();
} catch (e) {
alert(e); // ReferenceError!
}
If you want to:
Make sure the identifier exist, and
Make sure it is callable
You can:
if (typeof doSomething == 'function') {
doSomething();
}
The typeof operator can be safely used on identifiers that don't exist, additionally, by checking that doSomething is a function, you make sure that you will be able to invoke it.
Calling functions (or assignments, etc) in comparisons is generally a bad idea. People don't usually expect comparisons to have side effects. This case is simple enough that it might be justifiable, but if someone doesn't understand the convention they might have to ask on StackOverflow ;)

Categories

Resources