1

Typically, the solution to for..in's notorious caveat is something along the lines of:

for(var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
        foo(); bar(); baz();
    }
}

I feel like it would be cleaner to just do:

for(var prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;
}

The question is... Are they not functionally identical?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
wwaawaw
  • 6,867
  • 9
  • 32
  • 42

2 Answers2

4

They are functionally identical. Period.

As for the matter of style, Douglas and his JSLint say: don't use continue:

Avoid use of the continue statement. It tends to obscure the control flow of the function.

See http://javascript.crockford.com/code.html and search for "continue"

Oleg
  • 9,341
  • 2
  • 43
  • 58
  • 2
    Jesus christ, I hate crockford and his fearmongering. – wwaawaw Nov 19 '12 at 15:22
  • 1
    Indeed. It obscures the control flow of the function only for those incapable of basic reading. Which, admittedly, covers a big chunk of the JS userbase... – Lightness Races in Orbit Nov 19 '12 at 15:31
  • 1
    @adlwalrus: Crockford also seems to contradict Douglas on var declarations and spacing before the brackets in function declarations `function foo() {...}` versus `function bar () {...}`, to name a few. I think it really comes down to personal preference in these cases. (http://javascript.crockford.com/code.html#variable%20declarations) – Cerbrus Nov 20 '12 at 07:46
  • 1
    @Cerbrus There's no contradiction. Spacing before brackets, according to JSLint, is encouraged when the function literal is anonymous, such as `function () {}`. The reasoning behind this is quite solid and deserves a quote: "If the space is omitted, then it can appear that the *function's name is* **function**, which is an incorrect reading." I would also like to note, that this discussion went a bit outside of the scope of the question. Let's stop it at this point. Thanks. – Oleg Nov 20 '12 at 08:31
1

Yes, they are functionally identical.


I'd say the continue-less example is a little more semantic, though.

In the first example, you aren't negating the bool in your if, so, you have a typical
if(property){"Execute the rest of this loop"}
instead of
if(not property){"Do not execute the rest of this loop"}

Cerbrus
  • 70,800
  • 18
  • 132
  • 147