I'm learning JavaScript, and I feel like I understand hoisting decently enough, so I'm not asking what it is or how to do it or anything like that.
Is it good to hoist? If I can, should I be declaring my variables using
var foo = function() {};
Or should I be using this instead?
function foo() {}
When should I hoist and when should I not? Or does it even matter at all?
Hoisting is not something you can do or not do, it just happens in JavaScript.
Hoisting is the fact that all variable declarations get 'moved' to the top of the containing scope.
What you are talking about is using function expressions versus function declarations. Both styles are fine, just remember that they have a small difference in what gets hoisted:
var foo = function() {} // foo gets hoisted, but not the function itself
function foo(){} // the variable and the function get hoisted
For more information you can check out an article I write about hoisting in JavaScript: http://www.kenneth-truyers.net/2013/04/20/javascript-hoisting-explained/
There is no objective answer to this question. It comes down to personal preference.
In my own code, I prefer var foo = function() {};
. IMHO, avoiding function hoisting makes the code easier to understand, since the source code order matters.
Update: The ES6/ES2015 spec has the same recommendation for specific cases:
Prior to ECMAScript 2015, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement’s StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ECMAScript implementations permitted them. Unfortunately, the semantics of such declarations differ among those implementations. Because of these semantic differences, existing web ECMAScript code that uses Block level function declarations is only portable among browser implementation if the usage only depends upon the semantic intersection of all of the browser implementations for such declarations.
For example, the behavior of the following code was undefined in ES5 and differs between browsers/engines/implementations:
if (true) {
function foo() { return 1; }
} else {
function foo() { return 2; }
}
console.log(foo()); // `1` or `2`?
However, the following code has perfectly well-defined and interoperable behavior:
var foo;
if (true) {
foo = function() { return 1; }
} else {
foo = function() { return 2; }
}
console.log(foo()); // `1`
TL;DR Avoid function hoisting whenever you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With