const() function syntax

This probably seems like a quaint request but const functions are seeing a lot of use for their immutability, non-hoisting, and other benefits.

Why have we not seen syntax such as:

   const doSomething() {

   }

   // equivalent to:

   const doSomething = () => {

   }

I am not suggesting to replace the arrow syntax, simply add a shortcut that is a little more human readable to people coming from other languages. I hear a lot of people who refuse to use the const syntax despite having decent usecases for it because of the unnecessary arrow which does cost three-keystrokes plus the extra spacing with the arrow.

A "const function" in other languages usually means something substantially different - usually it indicates an idempotent function which is guaranteed to depend only on its arguments and no other state. It would probably actually be confusing to people from other languages if all it meant in JS was "you can't reassign this variable".

Plus it would mean we could never use this syntax space for anything else, such as an actual idempotent function. It would be a shame to do so when the benefit is just three characters of savings.

Why is non-hoisting a benefit, though? People don't usually re-assign their declarations, so hoisting means you can safely access your function declaration from anywhere. I really like writing code like this:

function doSomething() {
  doA();
  doB();
  doC();

  // technical details
  function doA() {
    // ...
  }
  function doB() {
    // ...
  }
  function doC() {
    // ...
  }
}

Relying on hoisting is considered (not by everyone, of course, but by many) to be poor style, and the Airbnb JavaScript style guide forbids doing so.

This is of course highly subjective, but i find code far more readable when I’ve read the import/require/definition of something before i encounter any uses.

1 Like

It's also subjective, but I like to start with a conceptual understanding of "what it does" before going into "how it does that", rather than getter immersed by all the implementation details upfront. I don't have strong opinions either way, but I don't think a gimped construct is necessarily a better construct—you can always use linters to restrict the freer form to what you want, but you can't do it the other way round.

(That's more about me ranting about the design pattern JavaScript is moving towards—for example Iterator.from should guarantee a branded object, and helpers should brand-check the receiver · Issue #224 · tc39/proposal-iterator-helpers · GitHub ^^)

Forcing a burden onto linters - which everyone should use but many people unfortunately do not - is always a worse choice than the language being proscriptive, imo.