Advanced JavaScript (ES6+)
1103 words
6 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Advanced JavaScript (ES6+) ## 🎯 Learning Objectives - Use arrow functions, template literals, destructuring - Understand let/const vs var - Use spread and rest operators - Work with Promises and async/await - Use ES6 modules (import/export) ## 1. let, const, and Block Scoping **TDZ (Temporal Dead Zone):** `let` a...

Advanced JavaScript (ES6+)
🎯 Learning Objectives
- Use arrow functions, template literals, destructuring
- Understand let/const vs var
- Use spread and rest operators
- Work with Promises and async/await
- Use ES6 modules (import/export)
1. let, const, and Block Scoping
javascript// var: function-scoped (avoid) var x = 10; // Can be redeclared, hoisted // let: block-scoped, can be reassigned let y = 20; y = 30; // OK // const: block-scoped, cannot be reassigned const z = 40; z = 50; // ERROR! // const does NOT make objects immutable const obj = { a: 1 }; obj.a = 2; // OK — const prevents reassignment, not mutation
TDZ (Temporal Dead Zone):
let and const are hoisted but not initialized. Accessing them before declaration throws ReferenceError.2. Arrow Functions
javascript// Traditional function function add(a, b) { return a + b; } // Arrow function const add = (a, b) => a + b; // Single parameter (no parens needed) const square = x => x * x; // No parameters const greet = () => 'Hello'; // Multiple statements (need braces and return) const sum = (a, b) => { const result = a + b; return result; };
Arrow vs Regular Functions:
- No
thisbinding: Arrow functions inheritthisfrom surrounding scope (lexical) - No
argumentsobject: Use rest parameters instead - Cannot be used as constructors (no
new) - No
prototypeproperty
javascriptfunction Person(name) { this.name = name; } const p = new Person('Alice'); // OK const PersonArrow = (name) => { this.name = name; // `this` is not bound }; // new PersonArrow('Alice'); // ERROR!
3. Template Literals
javascriptconst name = 'Alice'; const age = 25; // Old way: console.log('Name: ' + name + ', Age: ' + age); // Template literal (backticks): console.log(`Name: ${name}, Age: ${age}`); // Multi-line strings: const html = ` <div> <h1>${name}</h1> </div> `;
4. Destructuring
javascript// Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const person = { name: 'Alice', age: 25, city: 'Chennai' }; const { name, age, ...other } = person; console.log(name); // Alice console.log(age); // 25 console.log(other); // { city: 'Chennai' } // Renaming const { name: personName } = person; console.log(personName); // Alice // Default values const { country = 'India' } = person; console.log(country); // India (default since person doesn't have country)
5. Spread and Rest Operators (...)
javascript// Spread — expand an array/object const arr1 = [1, 2, 3]; const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5] const obj1 = { a: 1, b: 2 }; const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 } // Copy (shallow) const copy = { ...obj1 }; // Merge const merged = { ...obj1, ...obj2 }; // Rest — collect remaining parameters function sum(...numbers) { return numbers.reduce((total, n) => total + n, 0); } console.log(sum(1, 2, 3, 4)); // 10 // Rest with destructuring const [first, ...others] = [1, 2, 3, 4]; // first=1, others=[2,3,4]
6. Promises
javascript// Creating a Promise const fetchData = new Promise((resolve, reject) => { setTimeout(() => { const success = true; if (success) { resolve({ id: 1, name: 'Data' }); } else { reject(new Error('Failed')); } }, 1000); }); // Consuming a Promise fetchData .then(data => console.log(data)) .catch(error => console.error(error)) .finally(() => console.log('Done'));
7. Async/Await
javascript// async function returns a Promise async function getUser(id) { try { const response = await fetch(`/api/users/${id}`); if (!response.ok) throw new Error('Network error'); const user = await response.json(); return user; } catch (error) { console.error('Failed:', error); throw error; // Rethrow if needed } } // Using async/await with Promise.all (parallel) async function loadAll() { const [user, posts, comments] = await Promise.all([ fetch('/api/user').then(r => r.json()), fetch('/api/posts').then(r => r.json()), fetch('/api/comments').then(r => r.json()) ]); return { user, posts, comments }; }
8. ES6 Modules
javascript// math.js — export export const PI = 3.14159; export function add(a, b) { return a + b; } export default class Calculator { /* ... */ } // app.js — import import Calculator, { PI, add } from './math.js'; import * as MathUtils from './math.js'; // Namespace import
9. Practice Questions
Q1: What's the difference between var, let, and const?Answer:varis function-scoped, hoisted, can be redeclared.letis block-scoped, hoisted (TDZ), can be reassigned but not redeclared in same scope.constis block-scoped, cannot be reassigned (but objects can be mutated). Q2: How do arrow functions handlethisdifferently?Answer: Arrow functions don't have their ownthis. They inheritthisfrom the enclosing lexical scope. Regular functions getthisbased on how they're called (method, function, constructor). Q3: What does the spread operator do?Answer:...expands an iterable (array, object) into individual elements. Used for copying, merging, passing function arguments. Example:Math.max(...[1,5,3])is equivalent toMath.max(1,5,3). Q4: What is Promise.all?Answer: Takes an array of promises and returns a single promise that resolves when ALL input promises resolve, or rejects if ANY rejects. Used for parallel asynchronous operations. Q5: Convert this to an arrow function?javascriptconst numbers = [1, 2, 3]; const doubled = numbers.map(function(n) { return n * 2; });Answer:const doubled = numbers.map(n => n * 2);Q6: What's the output?javascriptconst [a, , b] = [1, 2, 3, 4]; console.log(a, b);Answer:1 3— destructuring skips the second element (the comma with no variable). Q7: How do you handle errors with async/await?Answer: Use try/catch blocks:javascriptasync function load() { try { const data = await fetch('/api'); } catch (error) { console.error(error); } }Q8: What's the difference between default and named exports?Answer: A module can have one default export (export default function) imported without braces (import X from './mod'). Named exports (export const X) require braces (import { X } from './mod').
📐 Key Concepts
| Feature | Syntax | Use Case |
|---|---|---|
| Arrow function | () => {} | Callbacks, array methods |
| Template literal | \text ${var}`` | String interpolation |
| Destructuring | [a,b] = arr, {a,b} = obj | Extract values |
| Spread | ...iterable | Copy, merge, spread |
| Rest | ...params | Variable arguments |
| Promise | new Promise((resolve, reject) => {}) | Async operations |
| async/await | async function() { await ... } | Cleaner async code |