Introduction
Arrow functions (also called fat arrow syntax) provide a concise way to write functions that contain a single expression. They’re perfect for simple operations and callbacks.Arrow Function Syntax
Use the=> operator to create a single-expression function:
Key Components
- Return type:
int- same as traditional functions - Function name:
multiplicarFlecha - Parameters:
(int a, int b)- same as traditional functions - Arrow operator:
=>- replaces the curly braces and return keyword - Expression:
a * b- automatically returned
Traditional vs Arrow Syntax
Traditional Function
Arrow Function
Both functions do exactly the same thing, but the arrow function is more concise.
Complete Example
When to Use Arrow Functions
Arrow functions are ideal for:
- Single-expression functions
- Simple calculations
- Getters and simple methods
- Callback functions
- Mapping and filtering operations
Common Use Cases
Mathematical Operations
String Operations
Boolean Operations
Void Functions
Arrow functions work with void return types too:Arrow Functions with Named Parameters
Arrow Functions in Collections
With Lists
With forEach
Limitations of Arrow Functions
Won’t Work
Will Work
Getters with Arrow Syntax
Arrow functions are commonly used for getters:Comparison Chart
Traditional Functions
Use when:
- Multiple statements needed
- Complex logic required
- Local variables needed
- Better for debugging
Arrow Functions
Use when:
- Single expression
- Simple calculations
- Callbacks
- Conciseness matters
Best Practices
Good arrow function examples:
- Getters and setters
- Simple calculations
- Callbacks and lambdas
- Mapping and filtering
- Converting or transforming data
Performance Note
Arrow functions and traditional functions have the same performance. The arrow syntax is purely syntactic sugar for writing more concise code.