bevacqua / js

:art: A JavaScript Quality Guide
https://ponyfoo.com
MIT License
2.93k stars 502 forks source link

Function declarations and hoisting. #22

Closed robmclarty closed 9 years ago

robmclarty commented 9 years ago

I'm confused why a function expression is worse than a function declaration (https://github.com/bevacqua/js#functions). You site hoisting as the reason why they're bad. But aren't function expressions better for this very reason? That is, by declaring the function as a variable, it will remain in the order that it is defined in the scope, rather than switching around as a function declaration would be hoisted above other variable definitions and make the code less clear.

Also, it seems that by defining a function in a variable, one would get better error feedback (for example if someone tried to use the function before it was declared they would get a TypeError).

See http://www.unicodegirl.com/function-statement-versus-function-expression.html

IMHO function expressions make for clearer code as it is closer to what the interpreter is seeing, making the code more predictable and thus easier to manipulate.

This may all be moot with ES6 now standardized and most of the community moving over to block-scoped let, but I'm just curious about your reasoning because I always thought about it the other way around.

bevacqua commented 9 years ago

I say that:

When declaring a function, always use the function declaration form instead of function expressions. Because hoisting.

They're worse because you get into a situation where you need to sort functions yourself.

robmclarty commented 9 years ago

Ok. Then doesn't that force you to structure your code in a more explicitly straightforward manner? ...which would make the execution order more obvious and clear?

I'd rather do a bit of extra work for clarity than save some keystrokes and leave magical hoisting functionality that the next guy might miss.

bevacqua commented 9 years ago

Sure, I'd rather not do things that force me into a corner. But style guides are opinions, everyone has one

robmclarty commented 9 years ago

That's cool. Yeah,I just wanted to gain some more insight into yours ;)