JavaScript / TypeScript Styleguide
Function Declarations vs Arrow Functions
Two ways to define functions in JavaScript. Explore the tradeoffs between traditional function declarations and modern arrow functions.
69%
Use Function Declarations
31%
Use Arrow Functions
Function Declarations
Traditional, hoisted, and with their own 'this' binding. The classic way to define functions.
Code Example
example.js (function declaration)
function calculateTotal(items) {
return items.reduce(function(sum, item) {
return sum + item.price;
}, 0);
}
function handleClick() {
console.log(this.name);
}Key Benefits
- Hoisted to the top of their scope
- Has its own 'this' binding
- Can be used as constructors with 'new'
- Named functions appear in stack traces
- More explicit and readable for some developers
- Required for generator functions
Statistics
Arrow Functions
Concise, lexically-scoped 'this', and perfect for callbacks and functional programming.
Code Example
example.js (arrow functions)
const calculateTotal = (items) =>
items.reduce((sum, item) => sum + item.price, 0);
const handleClick = () => {
console.log(this.name);
};Key Benefits
- Concise syntax, especially for one-liners
- Lexical 'this' binding (inherits from parent)
- Perfect for callbacks and array methods
- No 'arguments' object (use rest parameters)
- Cannot be used as constructors
- Ideal for functional programming patterns
Statistics
Additional Insights
More data points to help you make an informed decision for your team.
995
repositories analyzed