Working with JS got you Hoisted?

SO I had a conversation with a co-worker DC Hoth today about some JS funkiness. Not a uncommon thing with JS, eh? Any how, we had this code snippet and at frist blush, looked so innocent. That notion was shattered rather abruptly. The sample went something like this:

On first gaze you’d think line 9 would spit out what? 1 right? wrongo! What is happening here is that JavaScript ‘hoists’ variable definitions up to the top of the function. This means that in reality the above looks like this:

How to avoid this? For one, ‘var scope’ your locals at the top of your function as a best practice. This will help with undefined issues. Note to self….

This entry was posted in CSS3, Flex, HTML5, JavaScript. Bookmark the permalink.