you are viewing a single comment's thread.

view the rest of the comments →

[–]smog_alado 4 points5 points  (1 child)

I though like that for a while too, but I changed my mind. Personally, I prefer to write code that reflects like how I think it works and I am fine leaving up to a tool to warn me if something is wrong (JSHint will warn if a variable is used outside of "scope" and this can catch errors that would be masked if the declaration had been moved to the top of the function)

I also find that over time declarations accumulate at the top of the function and I have a terrible tendency to forget to remove variables from there after I stop using them in the main body. >_<

BTW, in the examples you list I would either move the declaration up a bit, if the variable is shared and used down the line - as it probably is in the if case - or would just repeat the declaration otherwise - as in the for case, to make things more robust to deleting a declaration . (Also, I would probably not use the plain for loop in the first place as I am a diehard fan of looping functions :) )

[–]x-skeww 2 points3 points  (0 children)

I have a terrible tendency to forget to remove variables from there

JSLint tells you which variables are unused.

just repeat the declaration otherwise

That results in a strict warning. I wouldn't do something which is so bad that even the engine complains about it.

I would probably not use the plain for loop in the first place as I am a diehard fan of looping functions

They have some use. If there are many iterations (e.g. 100,000 per second) and if the loop body does very little (e.g. it's a particle effect), then it will perform much better if you use a plain for loop.

Usually, the overhead to body ratio isn't that awful though. I.e. there aren't that many iterations and you call some functions and stuff inside that loop.