staafl

js variable declaration discussion

Apr 26th, 2013
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. <staafl> is there any reason to declare variables on the top of the function? // аз
  2. <freeone3000> staafl: No. Javascript variables are hoisted to function scope regardless of where they're declared.
  3. <staafl> I know about the different scoping semantics, but still don't see much benefit in pulling all variables to the beginning
  4. <yansanmo> it's for style only
  5. <staafl> yansanmo, i see
  6. <staafl> yansanmo, is it recommended style?
  7. <staafl> and is there any practical reason to follow it
  8. <jrajav> staafl: It's recommended by some, it's not by others... that's a kind of pointless question. :P
  9. <yansanmo> staafl, maybe because the engine will set every var identifier to the top of the function and set every identifier to undefined
  10. <jrajav> Second question's better, and yes there is
  11. <jrajav> The reason is that programmers might not be aware of the hoisting behavior and account for it
  12. <staafl> what "programmers"
  13. <jrajav> Particularly if they are used to more traditional scoping rules
  14. <yansanmo> >> console.log(a === undefined); var a;
  15. <ecmabot> yansanmo: undefined; Console: true
  16. <staafl> i mean, if they don't know *that*
  17. <jrajav> Well psh why do we have style at all then
  18. <jrajav> Work on minified code
  19. <yansanmo> >> console.log(a === undefined); var a = 1;
  20. <ecmabot> yansanmo: undefined; Console: true
  21. <jrajav> It's just the same reason you'll pay attention to proper indentation and naming conventions. Just so the code is easier to process and reason about. You don't need to do it if you don't want to.
  22. <jrajav> A lot of people prefer to declare variables closer to where they're actually used
  23. <jrajav> Personally I think that if you feel like your variable declaration are too far from where they're used, your function is too long anyway.
  24. <staafl> i'm asking about the reason to choose between different styles, not whether style is needed
  25. <jrajav> Part of style is avoiding "clever" obfuscation of language features
  26. <yansanmo> should I choose "i" or "index" ?
  27. <jrajav> I actually do use index when the code is simple enough :P
  28. <jrajav> Or a more appropriate, domain-specific name
  29. <staafl> a reason to declare variables as late as possible is so that any initial comments will be close to the usage
  30. <staafl> also, it informs the reader that the variable is not meant to be used before that point
  31. ...
Advertisement
Add Comment
Please, Sign In to add comment