---
source_hash: "16471991"
title: "Chapter 1: Variables and Scope"
weight: 310
---

# Chapter 1: Variables and Scope

## const and let vs var

In modern JavaScript, we no longer use `var`. We use:

- **`const`**: for values that do not change (most common case)
- **`let`**: for values that need to be reassigned

```javascript
// CORRECT - Modern JavaScript
const API_URL = "https://example.com/api";
const user = { name: "Jean" };

let counter = 0;
counter = counter + 1; // OK, let allows reassignment

// INCORRECT - avoid var
var oldStyle = "do not use";
```

### Warning: const does not mean immutable

`const` prevents **reassignment**, not **mutation**:

```javascript
const user = { name: "Jean" };

// FORBIDDEN - reassignment
user = { name: "Paul" }; // TypeError!

// ALLOWED - object mutation
user.name = "Paul"; // OK
user.age = 30;      // OK

const items = [1, 2, 3];
items.push(4);      // OK - array is modified
items = [5, 6];     // TypeError! - reassignment forbidden
```

### Comparison with PHP

```php
// PHP
const API_URL = "...";     // Constant (primitive values only)
$user = ["name" => "Jean"]; // Variable
```

```javascript
// JavaScript
const API_URL = "...";          // Constant
const user = { name: "Jean" };  // Also const! (object)
```

## Destructuring

Destructuring allows extracting values from objects or arrays in a single line.

### Object Destructuring

```javascript
const user = {
    name: "Jean",
    age: 30,
    city: "Paris"
};

// WITHOUT destructuring
const name = user.name;
const age = user.age;

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

// Rename a variable
const { name: userName } = user;
// userName = "Jean"

// Default value
const { country = "France" } = user;
// country = "France" (user.country does not exist)
```

### Array Destructuring

```javascript
const colors = ["red", "green", "blue"];

// WITHOUT destructuring
const first = colors[0];
const second = colors[1];

// WITH destructuring
const [first, second] = colors;
// first = "red", second = "green"

// Skip elements
const [, , third] = colors;
// third = "blue"
```

### Common usage in React

```javascript
// useState returns an array [value, function]
const [count, setCount] = useState(0);

// Component props
const MyComponent = ({ title, onClick }) => {
    // title and onClick extracted from props
};
```

### Comparison with PHP

```php
// PHP 7.1+
['name' => $name, 'age' => $age] = $user;
[$first, $second] = $colors;
```

## Spread Operator (...)

The spread operator (`...`) allows expanding an array or object.

### Spread on Arrays

```javascript
const fruits = ["apple", "pear"];
const vegetables = ["carrot", "leek"];

// Merge arrays
const food = [...fruits, ...vegetables];
// ["apple", "pear", "carrot", "leek"]

// Copy an array (shallow copy)
const fruitsCopy = [...fruits];

// Add elements
const moreFruits = [...fruits, "orange", "banana"];
```

### Spread on Objects

```javascript
const user = { name: "Jean", age: 30 };

// Copy an object
const userCopy = { ...user };

// Merge/extend an object
const userWithCity = { ...user, city: "Paris" };
// { name: "Jean", age: 30, city: "Paris" }

// Override a property
const updatedUser = { ...user, age: 31 };
// { name: "Jean", age: 31 }
```

### Critical usage in React

In React, we never modify state directly. We create a **new copy**:

```javascript
// INCORRECT - direct mutation
user.age = 31;
setUser(user); // React does not detect the change!

// CORRECT - new copy with spread
setUser({ ...user, age: 31 });
```

### Comparison with PHP

```php
// PHP - merge arrays
$food = array_merge($fruits, $vegetables);
$food = [...$fruits, ...$vegetables]; // PHP 7.4+

// PHP - merge associative arrays
$userWithCity = array_merge($user, ['city' => 'Paris']);
$userWithCity = [...$user, 'city' => 'Paris']; // PHP 8.1+
```

## Rest Parameters (...)

The same `...` operator is also used to collect arguments:

```javascript
// Collect all remaining arguments
function sum(first, ...others) {
    console.log(first);  // 1
    console.log(others); // [2, 3, 4, 5]
}

sum(1, 2, 3, 4, 5);

// Collect all remaining props
const Button = ({ label, ...otherProps }) => {
    return <button {...otherProps}>{label}</button>;
};
```

## Template Literals (backticks)

Template literals allow interpolation and multi-line strings:

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

// Interpolation
const message = `Hello ${name}, you are ${age} years old`;

// Expressions in interpolation
const info = `In 10 years, you will be ${age + 10} years old`;

// Multi-line
const html = `
    <div>
        <h1>${name}</h1>
        <p>Age: ${age}</p>
    </div>
`;
```

### Comparison with PHP

```php
// PHP
$message = "Hello $name, you are $age years old";
$message = "Hello {$name}, you are {$age} years old";

// JavaScript - note the backticks!
const message = `Hello ${name}, you are ${age} years old`;
```

## Exercises

### Exercise 1: Destructuring

Extract `name` and `email` from this object:

```javascript
const response = {
    data: {
        user: {
            name: "Jean",
            email: "jean@example.com",
            role: "admin"
        }
    }
};

// Your code here
```

**Solution:**

```javascript
const { data: { user: { name, email } } } = response;
// or in two steps:
const { user } = response.data;
const { name, email } = user;
```

### Exercise 2: Spread

Create a copy of `user` with `city` added and `age` updated:

```javascript
const user = { name: "Jean", age: 30 };

// Expected result: { name: "Jean", age: 31, city: "Paris" }
```

**Solution:**

```javascript
const updatedUser = { ...user, age: 31, city: "Paris" };
```

## Key Points to Remember

1. **Use `const` by default**, `let` only if reassignment is needed
2. **`const` does not prevent mutation** of objects/arrays
3. **Destructuring**: `const { a, b } = obj` or `const [x, y] = arr`
4. **Spread**: `{ ...obj }` to copy, `{ ...obj, newProp }` to extend
5. **Never mutate** state in React - always create a copy

[<- Back to module](/training/module1-javascript-es6) | [Next chapter: Functions ->](/training/module1-javascript-es6/fonctions)
