Are empty true blocks an idiom in JavaScript? - javascript

I just came across code that looks like this:
if (foo == "bar"){}else{
}
Is there a good reason for someone to write it that way instead of
if (foo != "bar") {
}
or am I just dealing with a raving lunatic (this is my assumption based on other things in the code).

[Edit]
There is no such convention in the JavaScript community. This is just bad code.
[Original "Answer" Below]
I prefer to use the following syntax when I am leaving a project:
if (foo == "bar") { /* 100 or so spaces */ } else {
}
The } else { segment is hopefully obscured off screen by text editors so that the code does the exact opposite of what it seems. This way I can ensure that the remaining development team curses my name and would never consider me for future development or support. =D

I don't see why JavaScript code should be different in this respect from any C-heritage language. I've not encountered this idiom before, and I really don't like it. I need to mentally parse the thing twice to make sure I've understood.
The only analogue I can think of is an empty default in a switch statement,with a copious comment to say "I thought about this and it's just fine."

If one of my developers wrote code that way, I'd throw it back at them with a reprimand and a copy of "Javascript: The Good Parts." I can't think of a single good reason for doing that.
Also, they should have written their comparison as if (foo === "bar"). Much better practice.
Edit a year and a half later:
Out of boredom I knocked together a jsperf just to see if there was any noticeable performance difference between the two methods shown in the OP, and [SPOILER WARNING] no there isn't.
http://jsperf.com/empty-blocks-in-if-else-statement

I have done it before.
This is when I might want to add some debug statements later.
Yes sure he could have done
if (foo != "bar"){
//something
}else{}
But isn't that just the same thing?
Back to the code you saw.
So what the programmer probably did is:
if (foo == "bar"){}
else{/*something*/}
Then later on when he wanted to add some debug information into the 1st part he would.
The logic still works and it is not flawed in the least bit. (in my opinion)

It's confusing for two reasons. The syntax is confusing because he's evaluating foo == bar just to do ... nothing? It seems unnecessary not to use the syntax you suggested. Visually it's also confusing because the empty block and the if evaluation are on one line, so if I were reading this code later I might gloss over things and assume the statement read as
if (foo == "bar"){
}
Which is the exact opposite of the code's intention. One possible explanation for this is that the programmer intended to go back and implement some code for foo == bar, but either didn't or forgot to do so.
My vote is for lunatic.

There is no good reason to do that.
On a side note, however, keep in mind that with loops there are sometimes cases where an empty block may be acceptable:
var i;
for (i = 0; document.getElementById("box" + i).value != ""; i++) { }
// do something with i

I tend to write chained if's like this:
if (a) {
} else if (b) {
// do something
} else if (c) {
// do something
} else if (d) {
// do something
}
Rather than:
if (!a) {
if (b) {
// do something
} else if (c) {
// do something
} else if (d) {
// do something
}
}
This makes the code more neat IMO.
Does it make sense?

Related

Unnecessary 'else' after 'return'. (No-else-return)

I am using es-lint to clean up the errors in my code. I have come across this error:
Unnecessary 'else' after 'return'. (No-else-return)
} else {
I have always used else statements after a return. Is there something I may be overlooking?
if (cctot <= 3 && cctot > 0) {
alert('Credit under $3.00 not allowed');
return Number.MIN_SAFE_INTEGER; // important to return 0 so we can check for these conditions for validation
} else {
cctot *= -1;
}
return precise(cctot);
What that is basically saying is that the else part of the if statement is unnecessary if there is a return in the if part.
Something like this is what it expects:
if (cctot <= 3 && cctot > 0) {
alert('Credit under $3.00 not allowed');
return Number.MIN_SAFE_INTEGER; // important to return 0 so we can check for these conditions for validation
}
cctot *= -1;
In general, this:
if (condition) {
return something;
} else {
// do another thing
}
return anotherThing;
is similar to:
if (condition) {
return something;
}
// do another thing
return anotherThing;
After the if with a return statement, there is no need for the else part as the code below the if will only run when the condition stated is not fulfilled.
It's a code style preference. You don't need the else and instead can put the else code directly below the if. This is because if the if succeeds, that's the end of the function, so the else code will never be reached anyway.
So this:
if (condition) {
return foo;
} else {
// do bar
}
return baz
is equivalent to this:
if (condition) {
return foo;
}
// do bar
return baz
This style seems to vary in different programming communities. Go developers will nearly always omit the else, while I've seen more JS devs include it.
While I prefer to leave off the else, it is again purely a matter of preference. Don't let it worry you too much. People may get dogmatic about this kind of thing, but it's really not that important.
While the rule correctly points out that the else block is unnecessary, and it is a style preference, I would add additional considerations for readability and most importantly scanability.
For the developer writing this code, and to the machine interpreting it, it may be a style point and that's it. But for the developer who needs to fix a bug, enhance a feature, do a code review, etc. the ability to quickly scan through the code and see the else blocks helps to identify branches of logic.
In a few lines of isolated code it is easy to see the intent, but among hundreds of lines of code having if else blocks can serve as useful identifiers, much like other common visual practices like indentation, line breaks, and naming conventions.
The return statement stops/terminates the current function. It's just saying that there's no need for 'else' since the execution of the function already stopped and if the 'if' condition doesn't succeed, it will still run any code underneath it.
As for best practice, I won't say it's a big of a deal always but with the code in your example, I won't use the else clause because it's simply not needed. I think it's good to understand what's happening under the hood and the reason behind best practices and not just following them.

javascript leaving an empty if statement

I would like to know if leaving an empty if statement for certain situations as:
else if(typeof console === 'undefined'){}
Just to have the code bypass the rest of the function It is an accepted and safe way to work or there are other recommendation practices for these cases?. Thank you.
It's fine and safe to leave if branches empty, the only thing I would add is a comment:
else if(typeof console === 'undefined')
{
//explanation why nothing has to go here
}
Without seeing the rest of the code I'm unsure how you're using this to "bypass the rest of the function", there may be a better way to do this.
From what information you've provided me, I can glean that the answer is "no". It will work, but it's bad style. If you would like to bypass the rest of the function, why not return; or put most of the logic in the if statement that pertains to it so that there is no bypassing at all?
I just had a case in which I chose to use an empty if-statement (professional context). I must agree though, there definitely is a technically cleaner solution. Still, since in a professional context time is important too, I chose to use the empty if-statement in my case, so I wanted to share my train of thought with you.
In my case I'm patching existing code with a variable that is used to skip already existing nested if-statements. The main function keeps running before and after the statement.
Original Code:
if(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
// ... code continues with variables set inside the statements.
Now we want to add a global Parameter to not validate anything. What are my options and why do they suck?
Solution A sucks because much work and less easy to read:
if(!bValidateNothing && bValidateA){
}elseif(!bValidateNothing && bValidateB){
}elseif(!bValidateNothing && bValidateC){
}
Solution B sucks because empty if-statement:
if(bValidateNothing){
// empty
}elseif(bValidateA){
}elseif(bValidateB){
}elseif(bValidateC){
}
Solution C sucks because it becomes too nested (in my case there have been some additional ifs in the original code):
if(!bValidateNothing){
if(bValidateA){
if(xx){
}elseif(xy){}
}elseif(bValidateB){
}elseif(bValidateC){
}
}
Solution D, the technically cleanest solution by adding additional functions, sucks because you need to split your code, which needs a lot of time, and may result in new errors.
(no pseudocode)
So, to answer the question "accepted and safe": it works, it's readable, safe and quick. Sometimes that has to be enough, considering the alternatives. If you have the time to avoid using it, I'd probably still recommend that instead.
Funny enough, the time I saved by using this quick way to implement my logic, has now been successfully spent adding my cents to this ten year old already answered question.
Just don't write a block for a case you don't want to handle.
If you only want to do something when console exists, then do that:
if(typeof console !== 'undefined'){
// your code
}
// else if(typeof console === 'undefined'){}
// you don't need that second part
Or maybe I didn't quite get your issue?
Same as Pioul's answer, but I'd add that imo checking existence in javascript looks much tidier with the !! (notnot) operator.
if(!!console){
// your code
}
// else if(!console){}
// you don't need that second part
Sometimes it is useful to have debugging information printed out:-
if(typeof console !== 'undefined'){
console.log("debug info");
}
Then, before releasing the code, simply comment out all the console.log's
// console.log("debug info");
This can be done with a macro.
It will leave an empty if statement. But this is not a compilation error so that's OK.
Note, that if you're going to comment out the line it is important that braces are used. Otherwise you'd have the next line dependent on the if statement which would be a bleeding shame.
Using an empty if statement can be a valid and accepted practice in certain situations.
For example, when working with a try-catch block, you may use an empty if statement to handle specific errors without disrupting the rest of the function. Additionally, it can be used for performance optimization by short-circuiting the evaluation of certain conditions.
Make sure that when using an empty if statement, it is properly commented to provide context and explanation for its use.
Example:
try {
// code that may throw an error
} catch (error) {
if(error instanceof SpecificError) {
// handle specific error without disrupting the rest of the function
}
}
Another example:
if(isFirstConditionTrue && isSecondConditionTrue && isThirdConditionTrue) {
// Do something
} else if(isFirstConditionTrue && isSecondConditionTrue) {
// Do nothing, because third condition is false
} else {
// handle other conditions
}
It's always a good practice to add comments explaining the purpose of each empty if statement and why you chose to use it in a certain scenario. It's not generally considered bad style as long as it serves a specific purpose and is well documented.

Is the break keyword in Javascript only meant for breaking out of loops?

One of my friends is teaching a programming class with Javascript and one of his assignments was to create a number guessing game. This was his example implementation:
funProgram: for(;;) {
numberGuesser: {
var num = (Math.random() * 100) | 0;
var guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", 0);
var guesses = 1;
guess: for(;;) {
higher: {
lower: {
if(guess === num) break guess;
if(guess > num) break lower;
guess = +prompt("Too low. Try again.", 0);
break higher;
}
guess = +prompt("Too high. Try again.", 0);
}
guesses++;
}
alert("You got it in " + guesses + " guesses! The number is " + num);
}
var again = prompt("Do you want to guess again (y/n)?", "y") === "y";
if(!again) break funProgram;
}
He told me that it's a good practice to label your code and wrap blocks around it so you can easily see what each section is doing. He also said labeled breaks and continues are much easier to read than unlabeled ones because you can know exactly what you are breaking out of. I've never seen any code patterns like this, so I'm not sure if this is true.
I've been using Javascript for a while and there are a few things in here that I've never seen before and some things that I still don't understand. I thought that the break keyword was specifically meant for breaking out of loops. The higher and lower blocks are not loops, but apparently you can still break out of it. How is that possible? It seems odd to me to break out of something that doesn't loop. Can you also break out of functions using the break keyword?
Breaks can in fact have labels (and do so accept them). However, I'm not sure who "He" is, but I would go as far as to say "He" is conveying his ideals of programming, rather than a specific standard. That is to say, there's no need to use labels, it just makes it more legible to that particular person. (And, IMHO, labels are reminiscent of the BASIC/GOTO days which usually results in Spaghetti Code).
Extra Credit: Ask your friend if they used to write in BASIC; I'm betting you'll get a "yes" (along with a lot of bad habits for the duration of the course--that's not to profile, I've just never had a good experience with BASIC/VB programmers following [current] coding patterns))
The break command is commonly used to exit loops, however if the code block is nested within a label, you're establishing yet another block which you can break from. It also gives you a bit more flexibility as to where the break is meant to exit from. For example:
for (;;){ // "for a"
for(;;){ // "for b"
break; // breaks "for b"
}
}
In this instance, break is only meant to exit the nested ("for b") loop. However:
myblock: {
for(;;){
for(;;){
break mybock; // breaks label "myblock"
}
}
}
In this case, break is actually exiting both loops because you're instructing it to quit the label block entirely. This would be almost like having:
function myblock(){
for(;;){
for(;;){
return; // exits function "myblock"
}
}
}
Where return exits the block similar to the way break myblock acts.
By the way, not for nothing, I find this a tad easier to read:
var again = true;
while (again){
var num = (new Date()).getMilliseconds() % 100,
guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", "1"),
guesses = 1;
while (num !== guess){
guesses++;
guess = +prompt((guess < num ? "Too low." : "Too high.") + " Try again.", guess);
}
alert("You got it in " + guesses + " guesses! The number is " + num);
again = prompt("Do you want to guess again? (y/n)", "y") == "y";
}
I can understand the code after a little research on label and break in javascript. However, I personally don't like that style of coding, mainly because the labelled block syntax is too similar to the literal object notation - which I use a lot. And even Mozilla's documentation on labels tell us to avoid them:
Labels are not very commonly used in JavaScript since they make programs harder to read an understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error.
Regarding your objective questions:
break can be used to exit for loops, while loops and case statements, as well as labelled blocks.
You cannot use break to exit a function, you must use return.
From MDN (bold emphasis mine):
The break statement includes an optional label that allows the program
to break out of a labeled statement. The break statement needs to be
nested within this labelled statement. The labelled statement can be
any block statement; it does not have to be preceded by a loop
statement.
So, yes, labels can be used outside of loops, but, no, you can't use them to return from a function.
Those break statements are being used in the same way that goto is used in older languages. And as Shark pointed out: you can also use them in switch statements, but not in functions.
It's probably confusing to you because he is using the labeled blocks in conjunction with infinite for(;;) loops.
Look at this article here for more information: http://james.padolsey.com/javascript/labelled-blocks-useful/

Is there a better way to write this mutiple or conditional?

I have the following IF statement in javascript:
if ( !(cmd === 'JustifyLeft' || cmd === 'JustifyRight' || cmd === 'JustifyCenter' || cmd === 'JustifyFull') )
Any suggestions on how it could be written in a cleaner way?
Thanks
if(!cmd.match(/^Justify(Left|Right|Center|Full)$/))
In response to a few comments you can also mimic your strict comparison with a small edit:
if( typeof cmd != 'String' || !cmd.match(/^Justify(Left|Right|Center|Full)$/))
This will react in the exact same way as your current code, ignoring anything that's not a string.
Personally I think it is highly unlikely that you will need it.
This sounds like a good situation to use a switch. Just be aware that switches only do equality checking (==) not identity checking (===), though this should be fine.
switch (cmd) {
case "JustifyLeft" :
case "JustifyRight" :
case "JustifyCenter" :
case "JustifyFull" :
// do something
break;
case "somethingElse" :
default:
// do something else
break;
}
I would create a IsJustifyCommand(s) method or create a command abstract class that has a IsJustifyCommand() method on it. Then the code will read like a description of what it is trying to do.
Using regex may be neat, but will lead to maintenance problems if someone that is not a hard-core JavaScript programmer has to work on the code. However if you have lots of cases when regex is a good solution, then use it, as anyone looking at the code will soon pick it up.
(However I am a C# programmer not a JavaScript programmer, but like most programmer I have to look at / edit JavaScript code sometimes. I think most JavaScript is maintained by none JavaScript programmers.)
I hate when something is written like that. First I look at the code and think "if cmd is equal to JustifyLeft or JustifyRight... then invert that and... if that's true do the thing.. so that means if it's JustifyLeft...". For me it takes alot of time and I have to re-read the line to be sure I got it right.
I think it's better to write.
if ((cmd !== 'JustifyLeft') && (cmd !== 'JustifyRight') && (cmd !== 'JustifyCenter') && (cmd !== 'JustifyFull'))
It might be a little more verbose but I find it easier to follow. I read it as "cmd can't be any of the Justify-strings". Checking a long boolean expression and then inverting the whole answer is irritating.
I like the solution from scragar, just wanted to give my thoughts about inverting a long boolean expression.

Is it worth the effort to have a function that returns the inverse of another function?

I have recently added a HasValue function to our internal javascript library:
function HasValue(item) {
return (item !== undefined && item !== null);
}
A during a convorsation with a coworker, we came up with the idea of also adding another function that would basically just be the inverse: perhaps HasNoValue, or IsNothing
If we ended up doing that we would have:
function HasNoValue(item) {
return (item === undefined || item === null);
}
function HasValue(item) {
return !HasNoValue(item);
}
However, we're not sure whether it is more readable to have both, or HasValue.
Which is more readable/preferred?
A:
if (HasValue(x) && !HasValue(y))
B:
if (HasValue(x) && HasNoValue(y))
I vastly prefer A to B. "!" is a programming idiom that should be understood by all.
If !HasValue(y) and HasNoValue(y) are guaranteed to be logically equivalent over the entire input range of y, then I would greatly prefer !HasValue(y).
I would hesitate to even have a function named HasNoValue(y) because inevitably someone will write !HasNoValue(y).
I'm voting "A" by far.
The additional maintenance burden of doing this for each and any boolean return function isn't worth it versus the well-understood and quite readable "!", and in fact I believe "B" is actually less readable, since it's so easy to miss the "No" in the middle of the name.
I know I'll be quite alone with this opinion and if I'd be faced with this choise in a collaborative project, I'd surely go with A, since it's quite obvious it's the right thing to do, but I have to say I do appreciate the verbosity of option B. Words are just infinitely easier to read and understand than symbolics, even if it's something as mundane as our beloved ol' exclamation point.
Especially now that IDE's have so much better intellisense than before, I usually tend to opt for far more verbosity than before with all naming. 9 times out of 10, readability trumps small performance differences, hands down.
Just for the sake of having less lines of code and because your function returns a Boolean, I'd say to go with method A. If you have to worry about readability, you can always try:
if ( HasValue(x) && !(HasValue(y)) )
I would say option A is clearer, you know exactly what it means.
I would stick with option A but thats just me.

Categories

Resources