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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With