An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
April 15, 2022 03:38 pm GMT
Original Link: https://dev.to/skinnypetethegiraffe/function-or-const-which-do-you-prefer-typescriptjavascript-apa
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'
OR
function
function doSomethingCool(): string { return 'yes';}
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);}
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.
Original Link: https://dev.to/skinnypetethegiraffe/function-or-const-which-do-you-prefer-typescriptjavascript-apa
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To