Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are empty true blocks an idiom in JavaScript?

Tags:

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).

like image 645
Chas. Owens Avatar asked Aug 24 '11 17:08

Chas. Owens


3 Answers

[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

like image 165
maerics Avatar answered Nov 17 '22 15:11

maerics


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."

like image 38
djna Avatar answered Nov 17 '22 14:11

djna


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

like image 3
Scott Avatar answered Nov 17 '22 13:11

Scott