DEV Community

Discussion on: Named functions vs Functions as variables in JavaScript

Collapse
 
isaacdlyman profile image
Isaac Lyman • Edited

I see some advantages to both, not just in terms of readability (which, as you've said, is the most important thing), but functionality.

With named-function syntax, the function becomes available at parse time. You can define it at the end of a scope and it will be available at the beginning of the scope. I sometimes prefer to put helper functions at the end of a scope, so that rules out function-as-variable syntax.

With function-as-var syntax, you can use the ❤️const❤️ keyword, which prevents it from being accidentally redefined later. It also lets you take advantage of the ES6 arrow function's inherited this behavior, which is good if that's what you want, or bad if you want to bind the function manually.

Also, don't forget the third option, ES6 method syntax:

const obj = {
  foo (bar) {
    // some code
  }
}

It's only available inside of object and class definitions, but I really like it.

I haven't committed entirely to any one of these syntaxes. I use whichever one seems to fit what I'm doing and makes my code easy to understand.