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
// 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:
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
const API_URL = "..."; // Constant (primitive values only)
$user = ["name" => "Jean"]; // Variable
// 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
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
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
// 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 7.1+
['name' => $name, 'age' => $age] = $user;
[$first, $second] = $colors;
Spread Operator (...)
The spread operator (...) allows expanding an array or object.
Spread on Arrays
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
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:
// 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 - 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:
// 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:
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
$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:
const response = {
data: {
user: {
name: "Jean",
email: "jean@example.com",
role: "admin"
}
}
};
// Your code here
Solution:
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:
const user = { name: "Jean", age: 30 };
// Expected result: { name: "Jean", age: 31, city: "Paris" }
Solution:
const updatedUser = { ...user, age: 31, city: "Paris" };
Key Points to Remember
- Use
constby default,letonly if reassignment is needed constdoes not prevent mutation of objects/arrays- Destructuring:
const { a, b } = objorconst [x, y] = arr - Spread:
{ ...obj }to copy,{ ...obj, newProp }to extend - Never mutate state in React - always create a copy