Module 1.1: ES6+ Essentials - The JavaScript Foundation for React

π― Learning Objectives
By the end of this lesson, youβll be able to:
- Use Arrow Functions as an alternative to traditional
functionsyntax. - Apply Destructuring to extract data from
Objects andArrays. - Understand and utilize the Spread/Rest Operator (
...). - Write dynamic strings with Template Literals.
- Handle data safely using Optional Chaining (
?.) and Nullish Coalescing (??).
1. Arrow Functions
1.1. Basic Syntax
Arrow Functions provide a more concise function syntax introduced in ES6.
// β Traditional Function (ES5)
function add(a, b) {
return a + b;
}
// β
Arrow Function (ES6+)
const add = (a, b) => {
return a + b;
};
// β
Implicit return (when there's only one expression)
const add = (a, b) => a + b;
// β
Single parameter (parentheses are optional)
const square = (x) => x * x;
// β
No parameters
const greet = () => 'Hello, World!';1.2. Arrow Functions and this Binding
// Regular Function - `this` depends on the function's call context
const user = {
name: 'Alice',
greet: function () {
console.log(`Hello, ${this.name}`);
},
};
user.greet(); // "Hello, Alice"
// Arrow Function - `this` inherits from the parent scope
const user2 = {
name: 'Bob',
greet: () => {
console.log(`Hello, ${this.name}`); // `this` is NOT user2
},
};
user2.greet(); // "Hello, undefined"Rule of Thumb:
| Scenario | Recommended Use |
|---|---|
| Callbacks (map, filter, forEach) | Arrow Function |
Object methods | Regular Function |
2. Destructuring
2.1. Object Destructuring
const user = { name: 'Alice', age: 25, email: 'alice@example.com' };
// β Traditional Approach
const name = user.name;
const age = user.age;
// β
Object Destructuring
const { name, age, email } = user;
// β
Renaming Variables (Aliasing)
const { name: userName } = user;
console.log(userName); // "Alice"
// β
Default Values
const { country = 'Vietnam' } = user;
console.log(country); // "Vietnam"
// β
Nested Destructuring
const company = {
name: 'TechCorp',
address: { city: 'Ho Chi Minh', district: 'District 1' },
};
const {
address: { city },
} = company;
console.log(city); // "Ho Chi Minh"2.2. Array Destructuring
const colors = ['red', 'green', 'blue'];
// β
Array Destructuring
const [first, second, third] = colors;
console.log(first); // "red"
// β
Skipping Elements
const [, , third] = colors;
console.log(third); // "blue"
// β
Rest pattern
const [first, ...rest] = colors;
console.log(rest); // ["green", "blue"]
// β
Swapping Values
let a = 1,
b = 2;
[a, b] = [b, a];
console.log(a, b); // 2, 12.3. Destructuring in Function Parameters
// Destructuring in parameters
const displayUser = ({ name, age }) => {
console.log(`${name} is ${age} years old`);
};
displayUser({ name: 'Alice', age: 25 });
// Output: "Alice is 25 years old"3. Spread and Rest Operator (...)
3.1. Spread Operator
The Spread operator spreads out the elements of an iterable (like an array) or the properties of an object.
// === ARRAY SPREAD ===
const original = [1, 2, 3];
const copy = [...original]; // Copy an array
const merged = [...arr1, ...arr2]; // Merge arrays
const withNew = [...original, 4]; // Add an element
// === OBJECT SPREAD ===
const user = { name: 'Alice', age: 25 };
const userCopy = { ...user }; // Copy an object
// Merge objects (properties from later objects override earlier ones)
const defaults = { theme: 'light', language: 'en' };
const userPrefs = { theme: 'dark' };
const settings = { ...defaults, ...userPrefs };
// { theme: "dark", language: "en" }
// Update property (immutably)
const updatedUser = { ...user, age: 26 };
// { name: "Alice", age: 26 }3.2. Rest Operator
The Rest operator collects multiple elements into an array or object.
// Rest in function parameters
const sum = (...numbers) => {
return numbers.reduce((acc, curr) => acc + curr, 0);
};
console.log(sum(1, 2, 3, 4)); // 10
// Rest in destructuring
const [first, ...remaining] = [1, 2, 3, 4, 5];
console.log(remaining); // [3, 4, 5]
const { name, ...otherInfo } = { name: 'Alice', age: 25, email: 'a@b.com' };
console.log(otherInfo); // { age: 25, email: "a@b.com" }4. Template Literals
const name = 'Alice';
const age = 25;
// β String Concatenation
const message = 'Hello, my name is ' + name + ' and I am ' + age + ' years old.';
// β
Template Literals
const message = `Hello, my name is ${name} and I am ${age} years old.`;
// β
Multi-line strings
const html = `
<div class="card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// β
Expressions
const total = `Total: $${(100 * 1.1).toFixed(2)}`; // "Total: $110.00"
// β
Ternary operators
const status = `User is ${age >= 18 ? 'adult' : 'minor'}`;5. Optional Chaining (?.)
Safely access nested properties or function calls.
const user = {
name: 'Alice',
address: {
city: 'Ho Chi Minh',
},
// No `company` property
};
// β Crashes if not checked
const companyName = user.company.name; // TypeError!
// β
Optional Chaining
const street = user?.address?.street; // undefined (no crash)
const companyName = user?.company?.name; // undefined (no crash)
const city = user?.address?.city; // "Ho Chi Minh"
// β
With Array access
const users = [{ name: 'Alice' }];
const thirdUser = users?.[2]?.name; // undefined
// β
With Function calls
const name = user.getName?.(); // undefined if method doesn't exist6. Nullish Coalescing (??)
Returns the right-hand value only if the left-hand side is null or undefined.
// β The Problem with || (which treats 0, "", and false as falsy)
const count = 0;
const displayCount = count || 10; // 10 (UNEXPECTED!)
// β
Nullish Coalescing (only checks for null/undefined)
const displayCount = count ?? 10; // 0 (CORRECT!)
// Comparison
const value1 = null ?? 'default'; // "default"
const value2 = undefined ?? 'default'; // "default"
const value3 = false ?? 'default'; // false
const value4 = 0 ?? 'default'; // 0
const value5 = '' ?? 'default'; // ""Combining with Optional Chaining
const user = {
settings: {
notifications: 0, // 0 is a valid value (notifications off)
},
};
// β Incorrect Logic
const notifications = user?.settings?.notifications || 5; // 5 (Wrong!)
// β
Correct Logic
const notifications = user?.settings?.notifications ?? 5; // 0 (Correct!)7. Summary
| Feature | Purpose |
|---|---|
| Arrow Functions | Write concise functions |
| Destructuring | Extract values from Objects/Arrays |
| Spread Operator | Expand arrays/objects, create copies, merge |
| Rest Operator | Collect multiple arguments/elements |
| Template Literals | String interpolation, multi-line strings |
| Optional Chaining | Safely access nested properties |
| Nullish Coalescing | Provide default values only for null/undefined |
Last updated on