If I want to "use" hoisting, is there a downside to using function expressions instead of regular function declarations? [closed]
Asked Answered
M

3

5

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?

Managua answered 21/4, 2015 at 9:14 Comment(3)
This question has been asked many times before. I will attempt to find a duplicate.Izolaiztaccihuatl
Both of those options hoist the variable/function.Henning
possible duplicate of var functionName = function() {} vs function functionName() {}Henning
L
6

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/

Langsyne answered 21/4, 2015 at 9:19 Comment(7)
The referenced article claims “If we look at Javascript however, there’s only two scopes: global and function scope.” This is false. Function declarations are block-scoped, as are lexical bindings (i.e. const and let). A better resource is 2ality.com/2015/02/es6-scoping.html.Neocene
That is the case for ES6, the article was written for ES5. I have updated the article.Langsyne
Thanks! This not only answers my question, but it also clears up a misconception that I had about hoisting. Very helpfulManagua
@MathiasBynens do you have any reference on that? AFAIK, block scope does not exist in ES5Langsyne
@Langsyne You’re right, it’s new in ES6 (even for function declarations). Given that, I stand by my earlier answer: avoid function hoisting whenever possible.Neocene
So, just to be clear, for function expression vs function declaration, should I be using one over the other whenever I can? For example, if I have a completely blank page, and I want a new function, which one should I default to, if any? var foo = function() or function foo(), or are each weighed equally with their own uses? @Mathias, you're saying avoid function hoisting whenever possible, does that mean I should default to var foo = function()?Managua
@Managua That is my personal preference, yes, and my answer explains why. But to each his own.Neocene
N
3

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.

Neocene answered 21/4, 2015 at 9:20 Comment(4)
You can't avoid "hoisting", it happens always, you can only change what gets hoisted (only variable or entire function)Langsyne
@Langsyne That is true, but it seems like the OP is already well aware of that, given the examples in his question. In my answer I called out function hoisting specifically, which can definitely be avoided.Neocene
IMO, the OP did not really understand the concept of hoisting. That's why I explained what hoisting is and how function declarations and expressions influence it.Langsyne
Thanks @MathiasBynens, this answered my question. I also thought the question meant more like "should I hoist when I don't need to hoist (yet)?", which is why I came here.Bordeaux
A
0

It is a good practice, to declare all variables at the top of a function, because of hoisting.... (not in ES6).

var foo = function() {}; and function foo() {} are two different things. the first one creates a variable and passes an anonymous function, the second one is 'just' a function.

You can't say, what definitly is the better one. It is depended of the context.

Alesha answered 21/4, 2015 at 9:20 Comment(2)
Could you explain a bit more what you mean by "(not in ES6)"?Henning
in ES6, let and const are block-scoped. So you should declare them first, when you need them (like in other languages, e.g. Java, C#)Alesha

© 2022 - 2024 — McMap. All rights reserved.