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

latobibor

Andr谩s T贸th

Posted on June 14, 2024

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.

馃挅 馃挭 馃檯 馃毄
latobibor
Andr谩s T贸th

Posted on June 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related