Bob Myers
2 min readApr 23, 2019

--

Unfortunately, this entire article is completely garbled. I’d suggest taking it down. You’re seriously confused about the relationship between function expressions, function declarations, arrow functions, and scope.

When you create a function with a name, that is a function declaration. The name may be omitted in function expressions, making that function “anonymous”.

No, a function with a name might be a function expression, as for example (function foo() { }). Whether or not a construct using the function keyword is a declaration or an expression is a matter of context; if it’s in an expression context, then by definition it’s a function expression, as in const f = function() { };. (Of course, a function declaration without a name is just a syntax error.)

In short, use function declarations when you want to create a function on the global scope and make it available throughout your code.

No. Whether or not something is a function declaration or a function expression has absolutely nothing to do with its scope. I can write const f = function() {}; (a function expression) at the outside scope and have it be globally (or module) scoped; I can write function f() { } (a function declaration) inside another function, in which case it is scoped to the enclosing function.

The only part of your aricle that is vaguely correct is that arrow functions are always anonymous and are always expressions.

The entire question posed by your title — when to use function expressions vs. function declarations — is itself odd. It’s like asking, when to eat an apple vs. an orange. If I want an apple, then I eat an apple; if I want an orange, then I eat an orange. In this case, it’s nothing more complicated than that I use a function expression when providing a function in an expression context, and I use a function declaration when declaring a function. The whole article, in other words, could have been a single sentence.

On the separate topic of hoisting, you’ve managed to pack a lot of misinformation into a few short sentences:

Hoisting refers to the availability of functions and variables “at the top” of your code, as opposed to only after they are created. The objects are initialized at compile time and available anywhere in your file.

Define “created”. Do you mean “declared”? And your use of the term “initialized” is exactly backwards. You refer to “the top of your code” and “in your file” whereas it’s typically about function scope.

--

--

Bob Myers
Bob Myers

Written by Bob Myers

Technologist, writer, Japanologist

No responses yet