Chapter 2: Functions

Arrow Functions

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

Basic Syntax

// 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

// 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 - anonymous function
$add = function($a, $b) {
    return $a + $b;
};

// PHP 7.4+ - arrow function (single expression)
$add = fn($a, $b) => $a + $b;
// 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.

// 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

// 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
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

// 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:

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

// 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
$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 - 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:

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

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

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

Exercises

Exercise 1: Arrow Functions

Convert to arrow functions:

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:

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:

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:

// 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 | Back to Module | Next Chapter: Asynchronous ->