DEV Community

Cover image for Why I (mostly) never write `const fn = () => {}`
András Tóth
András Tóth

Posted on

2

Why I (mostly) never write `const fn = () => {}`

A short article here on a subjective/objective manner.

Compare this:

const justAConstant = 1244430;
const conditionalValue = justAConstant > 13 ? 'yes' : 'no';
const updateResult = updateInDb(conditionalValue);
const updateInDb = value => fetch.post('/url', JSON.stringify(value));
Enter fullscreen mode Exit fullscreen mode

with this:

const justAConstant = 1244430;
const conditionalValue = justAConstant > 13 ? 'yes' : 'no';
const updateResult = updateInDb(conditionalValue);
function updateInDb(value) {
  return fetch.post('/url', JSON.stringify(value));
}
Enter fullscreen mode Exit fullscreen mode

Let's start with the trivial matter: while function is hoisted and you can declare wherever you want them (I like to define functions that solve partial problems under the function that solves the main problems) the order of constant declarations matter.

In the above example will throw this error: ReferenceError: can't access lexical declaration 'updateInDb' before initialization.

This is, as I said, trivial, very easy to fix. However there's something more appealing to me in the second version:

Separation of values and functions that operate over values. A quick glance at the second example will immediately show me where I can find the business logic, because they look different.

In UX design we plan for the ease of traversing the UI: things that are different must look different.

While your preference to use named functions vs. named unanymous functions saved as constants is subjective it is good to know that categorization of syntactical elements can be objectively confusing or clear.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay