Skip to main content

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

Arrow functions can only contain a single expression. You cannot:
  • Use multiple statements
  • Declare local variables
  • Use control flow statements (if, for, while)
  • Have multiple lines of code

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

  • Use arrow functions for simple, single-expression operations
  • Keep expressions short and readable
  • Don’t sacrifice readability for brevity
  • Use traditional syntax when logic becomes complex
  • Perfect for functional programming patterns
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.