function or const, which do you prefer? (TypeScript/JavaScript)

skinnypetethegiraffe

Bobby Plunkett

Posted on April 15, 2022

function or const, which do you prefer? (TypeScript/JavaScript)

When it comes to writing a function, which style do you prefer?

const

const doSomethingCool: string = () => 'yes'
Enter fullscreen mode Exit fullscreen mode

OR

function

function doSomethingCool(): string {
  return 'yes';
}
Enter fullscreen mode Exit fullscreen mode

My Thoughts

Personally, after years of using const, I have recently switched back over to function for a few reasons.

  • The intent is clear and concise, so that readers quickly differentiate between variables and functions. The faster you know what is going on, the better right?
  • Function hoisting, meaning it lets you use a function before you declare it in your code, where with const it will be undefined until it has been reached in the execution.
    • Also hoisting issues related to using function in bundling tools is no longer the issue it once was
  • Named functions show up in stack trace messages, which is handy

Edge-cases

While I have switched to using function in most cases, arrow functions still serve a important purpose in my codebase. Such as providing callbacks to high order functions, such as map, reduce, forEach, etc...

function iStillLikeArrows(users: Array<User>): Array<string> {
  return users.map(u => u.name);
}
Enter fullscreen mode Exit fullscreen mode

What Are Your Thoughts?

I would love to hear other opinions on this topic, and see different reasons/viewpoints as to why to favor one side more than the other.

Also remember, no one is wrong choosing one or the other, it's a personal preference.

💖 💪 🙅 🚩
skinnypetethegiraffe
Bobby Plunkett

Posted on April 15, 2022

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

Sign up to receive the latest update from our blog.

Related