NelsonLabs
JavaScript Basics/Modern JavaScript (ES6+)

Modern JavaScript (ES6+)

ES6 (ECMAScript 2015) and the updates that followed fundamentally modernised JavaScript. These features aren't optional extras — they're the standard way the language is written today.

Destructuring
javascript
// Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first = 10, second = 20, rest = [30, 40, 50]

// Object destructuring
const { name, age, city = "Nairobi" } = user;  // default value
const { name: userName } = user;                // rename

// In function parameters (very common in React)
function CourseCard({ title, duration, level }) {
  return `${title} — ${duration} — ${level}`;
}
Spread and rest
javascript
// Spread arrays
const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [...a, ...b];  // [1, 2, 3, 4, 5, 6]

// Spread objects
const defaults = { theme: "dark", lang: "en" };
const settings = { ...defaults, lang: "sw", fontSize: 16 };
// { theme: "dark", lang: "sw", fontSize: 16 }

// Clone without reference issues
const original = { name: "Nelson" };
const copy = { ...original };  // shallow copy

// Rest in function params
function log(first, ...others) {
  console.log(first);    // first arg
  console.log(others);   // all remaining args as array
}
Template literals, optional chaining, nullish coalescing
javascript
// Template literals — embed expressions in strings
const name = "Nelson";
const course = "JavaScript";
console.log(`Hello, ${name}! Welcome to ${course}.`);

// Multi-line strings
const html = `
  <div class="card">
    <h3>${course.title}</h3>
    <p>${course.description}</p>
  </div>
`;

// Optional chaining — don't throw if property doesn't exist
const city = user?.address?.city;           // undefined instead of TypeError
const firstCourse = user?.courses?.[0];    // safe array access
user?.greet?.();                            // safe method call

// Nullish coalescing — fallback only on null or undefined
const name = user.name ?? "Anonymous";     // "Anonymous" only if null/undefined
const port = process.env.PORT ?? 3000;