JavaScript ES6 – Why Use `const foo = () => {}` Instead of `function foo() {}`

es6functionsjavascript

Edit added 2+ years later

I "checked" the @dandavis answer because it answers my original question, giving reasons to prefer const foo. However, I am completely convinced by the @Wayne Bloss answer that function foo() is generally superior.

Original Question here

For example, in this Redux video, the instructor always uses syntax like

const counter = (state=0, action) => {
   ... function body here
}

where I would just use the "traditional"

function counter(state=0, action) {
   ... function body here
}

Which is actually shorter and, IMO, clearer. It's easier to scan the fairly even and structured left edge of the page for the word "function" than scan the raggedy right edge for a small "=>".

Other than this, and trying to be objective, not opinion, is there some useful difference or advantage to the newfangled syntax?

Best Answer

Function statements (named functions, 2nd syntax shown) are hoisted to the top of the full lexical scope, even those behind arbitrary and control blocks, like if statements. Using const (like let) to declare a variable gives it block scope, stops the full hoisting (hoisting to mere block), and ensures it cannot be re-declared.

When concatenating scripts together, or some using other package-building tools, function hoisting can break conflicting scripts in ways that are difficult to debug as it fails silently. A re-declared const will throw an exception before the program can run, so it's much easier to debug.