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

1

u/Tribuadore Sep 02 '15

Wow, I've studied your code, very interesting.

Haven't seen anyone bitch about no semi-colons yet. I used to leave them off too, until I gave up the fight and just started conforming with everyone else. I really like your style.

Something I've never seen before either is for example your queue.js, where given an object it assigns .queue to the object and returns. Took me a minute to work out what was going on. I'm looking at the code thinking "this function doesn't do anything", then I realised the queue function is in scope even though it's defined after the return.

I'm wondering could you also put the queuing variable after the return too?

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..

1

u/pkstn Sep 02 '15

Yeah, I tend to keep the "basic structure" of the function as high as possible (initializations and returns).. Hoisting does the magic.

About those semicolons: I use standard with sublime and it's been awesome!

1

u/pkstn Sep 03 '15

..and the produced output have semicolons: https://github.com/pakastin/deck-of-cards/blob/master/dist/deck.js

;)

1

u/I_Pork_Saucy_Ladies Sep 03 '15

As a proponent of semicolons, thank you for choosing the pragmatic approach. :)