Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <staafl> is there any reason to declare variables on the top of the function? // аз
- <freeone3000> staafl: No. Javascript variables are hoisted to function scope regardless of where they're declared.
- <staafl> I know about the different scoping semantics, but still don't see much benefit in pulling all variables to the beginning
- <yansanmo> it's for style only
- <staafl> yansanmo, i see
- <staafl> yansanmo, is it recommended style?
- <staafl> and is there any practical reason to follow it
- <jrajav> staafl: It's recommended by some, it's not by others... that's a kind of pointless question. :P
- <yansanmo> staafl, maybe because the engine will set every var identifier to the top of the function and set every identifier to undefined
- <jrajav> Second question's better, and yes there is
- <jrajav> The reason is that programmers might not be aware of the hoisting behavior and account for it
- <staafl> what "programmers"
- <jrajav> Particularly if they are used to more traditional scoping rules
- <yansanmo> >> console.log(a === undefined); var a;
- <ecmabot> yansanmo: undefined; Console: true
- <staafl> i mean, if they don't know *that*
- <jrajav> Well psh why do we have style at all then
- <jrajav> Work on minified code
- <yansanmo> >> console.log(a === undefined); var a = 1;
- <ecmabot> yansanmo: undefined; Console: true
- <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.
- <jrajav> A lot of people prefer to declare variables closer to where they're actually used
- <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.
- <staafl> i'm asking about the reason to choose between different styles, not whether style is needed
- <jrajav> Part of style is avoiding "clever" obfuscation of language features
- <yansanmo> should I choose "i" or "index" ?
- <jrajav> I actually do use index when the code is simple enough :P
- <jrajav> Or a more appropriate, domain-specific name
- <staafl> a reason to declare variables as late as possible is so that any initial comments will be close to the usage
- <staafl> also, it informs the reader that the variable is not meant to be used before that point
- ...
Advertisement
Add Comment
Please, Sign In to add comment