0
function test() {
   console.log("1")
}

vs.

let test = function () {
   console.log("1")
}

I know this may be preference but I'm asking because I had an interview in which the interviewee said "I noticed you use function declarations exclusively which isn't a great practice". I asked for more clarification as to "why" but he never gave a reason.

I thought the only difference was that function expressions do not get hoisted up as where function declarations do get hoisted so I always opt for function declarations. Am I missing an advantage of function expressions that I don't know?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
RicardoAlvveroa
  • 226
  • 1
  • 8
  • 1
    Except in [the case of declarations inside blocks](https://stackoverflow.com/questions/31419897/what-are-the-precise-semantics-of-block-level-functions-in-es6), it's mainly just a stylistic choice. One exception: arrow functions, which are often very useful due to how they work with `this`, cannot be declarations, they must be used as expressions – CertainPerformance Jan 10 '21 at 21:23
  • 1
    "but he never gave a reason" ... maybe there is none then ... – Jonas Wilms Jan 10 '21 at 21:23
  • I can think of a few: 1: Hoisting is unpredictable for non-JS devs; 2: `function foo() {}; var foo = 2; foo = "a"` is valid code; `const foo = () => {}; var foo = 2;` (this is why I insist on using expressions with `const` in my code); 3: And of course there's `this` confusion (no need to do `var that = this` junk with arrow functions). – Zac Anger Jan 10 '21 at 21:23
  • 1
    @ZacAnger That's partially a problem due to using the essentially-obsolete `var`. With `let` you get `Identifier 'foo' has already been declared` – CertainPerformance Jan 10 '21 at 21:24
  • @CertainPerformance True! But some people still use `var` for some unknown reason – Zac Anger Jan 10 '21 at 21:26
  • There are pros and cons for both (and the combination of the two). Not having a named function makes stack traces incrementally more annoying, though. – Dave Newton Jan 10 '21 at 21:30
  • "*I noticed you use function declarations exclusively which isn't a great practice*" - generally using function declarations is a *good* practice. They're concise, hoisted, and declarative. Only using them *exclusively*, even in cases where an arrow function would be better, is a problem. – Bergi Jan 10 '21 at 21:31

0 Answers0