Skip to Content
Module 1: Modern JS & TypeScript1.1 ES6+ Essentials

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

Banner for ES6+ Essentials, showcasing modern JavaScript concepts like arrow functions, destructuring, and template literals.

🎯 Learning Objectives

By the end of this lesson, you’ll be able to:

  • Use Arrow Functions as an alternative to traditional function syntax.
  • Apply Destructuring to extract data from Objects and Arrays.
  • 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:

ScenarioRecommended Use
Callbacks (map, filter, forEach)Arrow Function
Object methodsRegular 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, 1

2.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 exist

6. 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

FeaturePurpose
Arrow FunctionsWrite concise functions
DestructuringExtract values from Objects/Arrays
Spread OperatorExpand arrays/objects, create copies, merge
Rest OperatorCollect multiple arguments/elements
Template LiteralsString interpolation, multi-line strings
Optional ChainingSafely access nested properties
Nullish CoalescingProvide default values only for null/undefined
Last updated on