r/javascript • • Sep 02 '15

HTML5 Deck of Cards. 100% vanilla JS.

http://pakastin.github.io/deck-of-cards/
368 Upvotes

185 comments sorted by

View all comments

Show parent comments

4

u/randfur Sep 02 '15

That's JavaScript's function hoisting where function definitions are implicitly moved to the top of their scope. Variables get hoisted to the top of their scope as well with the value undefined, it isn't until the point in the code that you specify that they get assigned something else. This means you can use variables before you've assigned them and they'll have the value undefined.

2

u/pkstn Sep 02 '15

Yes, that's true. In this case it's not possible to define queueing after return:

return target

var queueing = []

Queueing would get hoisted, but the value would be undefined - I think. Function definitions work a little differently. Although some old IE might crash and burn, but minification (uglifyjs) should fix the order, I think..

4

u/MrBester Sep 02 '15 edited Sep 02 '15

queueing would get hoisted, but the value would be undefined - I think.

Correct.

While you know what you're doing, newer developers may not. Hence I advocate declaring vars (uninitialised until you need them), internal functions, then the meat of the main function with returns liberally spread around.

Anything to minimise the slightest possibility that old IE will cough. It already has enough ways, so why give it more?

You also get to see at a glance just how much you're declaring - instead of picking through the code - so you can tell if you really ought to refactor it...

1

u/pkstn Sep 03 '15

You are right..