---
source_hash: "88b1bd94"
title: "Chapter 2: Functions"
weight: 320
---

# Chapter 2: Functions

## Arrow Functions

Arrow functions are a shorthand syntax for functions. They are ubiquitous in React.

### Basic Syntax

```javascript
// Traditional function
function add(a, b) {
    return a + b;
}

// Equivalent arrow function
const add = (a, b) => {
    return a + b;
};

// Short syntax (implicit return)
const add = (a, b) => a + b;
```

### Syntax Rules

```javascript
// Single parameter: parentheses optional
const double = x => x * 2;
const double = (x) => x * 2; // equivalent

// Zero parameters: parentheses required
const sayHello = () => "Hello";

// Multiple parameters: parentheses required
const add = (a, b) => a + b;

// Multi-line body: braces + explicit return
const calculate = (a, b) => {
    const sum = a + b;
    const product = a * b;
    return { sum, product };
};

// Returning an object directly: parentheses around
const createUser = (name) => ({ name, createdAt: new Date() });
// Without parentheses, JS thinks {} is the function body!
```

### Comparison with PHP

```php
// PHP - anonymous function
$add = function($a, $b) {
    return $a + $b;
};

// PHP 7.4+ - arrow function (single expression)
$add = fn($a, $b) => $a + $b;
```

```javascript
// JavaScript - arrow function
const add = (a, b) => a + b;
```

## Difference from Traditional Functions

Arrow functions have one major difference: they **do not have their own `this`**.

```javascript
// Problem with traditional function
const obj = {
    name: "Jean",
    greet: function() {
        setTimeout(function() {
            console.log(this.name); // undefined! 'this' has changed
        }, 1000);
    }
};

// Solution with arrow function
const obj = {
    name: "Jean",
    greet: function() {
        setTimeout(() => {
            console.log(this.name); // "Jean" - arrow preserves 'this'
        }, 1000);
    }
};
```

In React, this simplifies many things (we'll come back to this).

## Default Parameters

```javascript
// Default value if parameter is not provided
function greet(name = "Visitor") {
    return `Hello ${name}`;
}

greet();        // "Hello Visitor"
greet("Jean");  // "Hello Jean"

// With arrow function
const greet = (name = "Visitor") => `Hello ${name}`;

// Default parameter using another parameter
const createUser = (name, role = "user", id = Date.now()) => ({
    name,
    role,
    id
});
```

### Comparison with PHP

```php
// PHP
function greet($name = "Visitor") {
    return "Hello $name";
}
```

## First-Class Functions (Callbacks)

In JavaScript, functions are values. You can:

- Store them in variables
- Pass them as arguments to other functions
- Return them from functions

### Passing a Function as Argument

```javascript
// Function that takes another function as parameter
function executeWithLogging(fn, value) {
    console.log(`Execution with: ${value}`);
    const result = fn(value);
    console.log(`Result: ${result}`);
    return result;
}

const double = x => x * 2;
executeWithLogging(double, 5);
// "Execution with: 5"
// "Result: 10"
```

### Array Methods with Callbacks

These methods are **essential** in React:

```javascript
const numbers = [1, 2, 3, 4, 5];

// map - transform each element
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// filter - keep elements that pass the test
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]

// find - find the first element
const firstBig = numbers.find(n => n > 3);
// 4

// some - at least one element passes the test
const hasEven = numbers.some(n => n % 2 === 0);
// true

// every - all elements pass the test
const allPositive = numbers.every(n => n > 0);
// true

// reduce - reduce to a single value
const sum = numbers.reduce((acc, n) => acc + n, 0);
// 15
```

### Usage in React

```javascript
// Display a list
const users = [
    { id: 1, name: "Jean" },
    { id: 2, name: "Marie" }
];

// In a React component
return (
    <ul>
        {users.map(user => (
            <li key={user.id}>{user.name}</li>
        ))}
    </ul>
);

// Filter and display
const activeUsers = users.filter(u => u.active);
return (
    <ul>
        {activeUsers.map(user => (
            <li key={user.id}>{user.name}</li>
        ))}
    </ul>
);
```

### Comparison with PHP

```php
// PHP
$doubled = array_map(fn($n) => $n * 2, $numbers);
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($acc, $n) => $acc + $n, 0);
```

```javascript
// JavaScript - chainable methods
const result = numbers
    .filter(n => n > 2)
    .map(n => n * 2)
    .reduce((acc, n) => acc + n, 0);
```

## Shorthand Property Names

When the property name is the same as the variable name:

```javascript
const name = "Jean";
const age = 30;

// WITHOUT shorthand
const user = {
    name: name,
    age: age
};

// WITH shorthand
const user = { name, age };
// { name: "Jean", age: 30 }

// Mixed
const user = {
    name,
    age,
    city: "Paris" // no shorthand here
};
```

## Shorthand Method Names

```javascript
// WITHOUT shorthand
const obj = {
    greet: function() {
        return "Hello";
    }
};

// WITH shorthand
const obj = {
    greet() {
        return "Hello";
    }
};
```

## Exercises

### Exercise 1: Arrow Functions

Convert to arrow functions:

```javascript
function multiply(a, b) {
    return a * b;
}

function isEven(n) {
    return n % 2 === 0;
}

function createGreeting(name) {
    return {
        message: `Hello ${name}`,
        timestamp: Date.now()
    };
}
```

**Solution:**

```javascript
const multiply = (a, b) => a * b;

const isEven = n => n % 2 === 0;

const createGreeting = name => ({
    message: `Hello ${name}`,
    timestamp: Date.now()
});
```

### Exercise 2: Array Methods

With this array of users:

```javascript
const users = [
    { id: 1, name: "Jean", age: 25, active: true },
    { id: 2, name: "Marie", age: 30, active: false },
    { id: 3, name: "Pierre", age: 35, active: true },
    { id: 4, name: "Sophie", age: 28, active: true }
];
```

1. Get an array of names only
2. Filter active users over 26 years old
3. Calculate the sum of ages

**Solution:**

```javascript
// 1. Names
const names = users.map(u => u.name);
// ["Jean", "Marie", "Pierre", "Sophie"]

// 2. Active > 26 years
const filtered = users.filter(u => u.active && u.age > 26);
// [{ id: 3, ... }, { id: 4, ... }]

// 3. Sum of ages
const totalAge = users.reduce((sum, u) => sum + u.age, 0);
// 118
```

## Key Points to Remember

1. **Arrow functions**: `(params) => expression` or `(params) => { statements }`
2. **Implicit return**: without braces, the value is returned automatically
3. **Returning an object**: `() => ({ key: value })` (parentheses required)
4. **Callbacks**: functions can be passed as arguments
5. **map, filter, reduce**: essential methods for array manipulation
6. **Shorthand**: `{ name }` is equivalent to `{ name: name }`

[<- Previous Chapter](/training/module1-javascript-es6/variables-scope) | [Back to Module](/training/module1-javascript-es6) | [Next Chapter: Asynchronous ->](/training/module1-javascript-es6/asynchrone)
