function* numbers() {
yield 1;
yield 2;
yield 3;
}
const generator = numbers();
console.log(generator.next());
console.log(generator.next());Output:
{ value: 1, done: false }{ value: 2, done: false }After all values are consumed:
{ value: 3, done: false }{ value: undefined, done: true }Important:
Calling a generator function doesn't immediately execute its body. It returns a generator object.
57. What are iterators?
An iterator is an object that provides a way to access values one at a time using the
next() method.Example:
const numbers = [10, 20, 30];
const iterator = numbers[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
Output:
{ value: 10, done: false }{ value: 20, done: false }The iterator eventually returns:
{ value: undefined, done: true }Common Iterables:
• Arrays
• Strings
• Maps
• Sets
That's why they can be used with
for...of.for (const number of numbers) {
console.log(number);
}58. What is destructuring assignment?
Destructuring assignment allows values to be extracted from arrays or objects and assigned to variables.
Object Example:
const user = {
name: "Deepak",
age: 25
};
const { name, age } = user;Array Example:
const numbers = [10, 20];
const [a, b] = numbers;
Why Use It?
It makes code shorter and easier to read, especially when working with API responses and function parameters.
59. What is dynamic import?
Dynamic import allows a JavaScript module to be loaded when it is needed, instead of loading it immediately.
It uses:
import()Example:
async function loadModule() {
const module = await import("./math.js");
console.log(module.add(10, 20));
}Important:
Unlike a static import:
import { add } from "./math.js";dynamic imports return a Promise.
Common Uses:
• Lazy loading
• Code splitting
• Loading features only when required
• Improving initial page performance
60. What are ES6 modules?
ES6 modules provide a standard way to divide JavaScript applications into separate files.
They use
export and import.Export:
// math.js
export function add(a, b) {
return a + b;
}
Import:
// app.js
import { add } from "./math.js";
console.log(add(10, 20));
Default Export:
export default function greet() {
console.log("Hello");
}Import:
import greet from "./greet.js";
Benefits:
✅ Code organization
✅ Reusability
✅ Encapsulation
✅ Easier maintenance
✅ Avoids unnecessary global variables
❤️ Double Tap For Part 7