es6

es6

Top Interview Questions

About es6

ES6, also known as ECMAScript 2015, is a major update to JavaScript that significantly improved the language by adding new features, syntax enhancements, and better support for large-scale application development. Before ES6, JavaScript (ES5) lacked many modern programming constructs, making code harder to maintain, scale, and read. ES6 addressed these limitations by introducing cleaner syntax, modularity, better variable scoping, and improved asynchronous programming capabilities.

ES6 was released in 2015 by ECMA International, the organization responsible for standardizing JavaScript. Since then, ES6 has become the foundation for modern JavaScript development and is widely supported by all major browsers and JavaScript runtimes like Node.js.


Key Features of ES6

1. Let and Const

One of the most important additions in ES6 is the introduction of let and const for variable declaration.

  • let allows block-scoped variables, unlike var which is function-scoped.

  • const is used to declare constants whose values cannot be reassigned.

Example:

let count = 10;
const PI = 3.14;

Block scoping helps prevent bugs caused by variable hoisting and accidental re-declaration.


2. Arrow Functions

Arrow functions provide a shorter syntax for writing functions and automatically bind the this keyword to the surrounding context.

Example:

const add = (a, b) => a + b;

Benefits:

  • Cleaner syntax

  • No need for function keyword

  • Lexical this binding, especially useful in callbacks


3. Template Literals

Template literals allow embedded expressions and multi-line strings using backticks (`).

Example:

let name = "Yash";
let message = `Hello ${name}, welcome to ES6!`;

Advantages:

  • String interpolation

  • Multi-line strings

  • Improved readability


4. Destructuring Assignment

Destructuring allows extracting values from arrays or objects into variables easily.

Example:

const user = { name: "Amit", age: 25 };
const { name, age } = user;

This feature reduces repetitive code and improves clarity.


5. Default Parameters

Functions can now have default parameter values, avoiding manual checks for undefined.

Example:

function greet(name = "Guest") {
    return `Hello, ${name}`;
}

This leads to more robust and readable function definitions.


6. Rest and Spread Operators

The rest operator (...) collects multiple values into an array, while the spread operator expands elements.

Example:

function sum(...numbers) {
    return numbers.reduce((a, b) => a + b);
}

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5];

These operators simplify array and function argument handling.


7. Classes

ES6 introduced a class syntax that provides a cleaner way to implement object-oriented programming.

Example:

class Person {
    constructor(name) {
        this.name = name;
    }
    greet() {
        return `Hello, ${this.name}`;
    }
}

Although JavaScript is still prototype-based, classes make OOP concepts more accessible and readable.


8. Modules (Import and Export)

ES6 added native support for modules, allowing code to be split into reusable files.

Example:

// math.js
export function add(a, b) {
    return a + b;
}

// main.js
import { add } from './math.js';

Modules improve:

  • Code organization

  • Reusability

  • Maintainability


9. Promises

Promises simplify asynchronous programming and reduce callback hell.

Example:

const fetchData = () => {
    return new Promise((resolve, reject) => {
        resolve("Data received");
    });
};

fetchData().then(data => console.log(data));

Promises make async code easier to understand and manage.


10. Enhanced Object Literals

ES6 allows shorthand property names and method definitions.

Example:

let name = "Raj";
let user = {
    name,
    greet() {
        return "Hello!";
    }
};

This reduces boilerplate code and improves readability.


11. For...of Loop

The for...of loop provides a simpler way to iterate over iterable objects like arrays, strings, and maps.

Example:

for (let value of [1, 2, 3]) {
    console.log(value);
}

This loop is cleaner than traditional for loops for many use cases.


12. Map and Set

ES6 introduced new data structures:

  • Map: Key-value pairs with any type of key

  • Set: Collection of unique values

Example:

let set = new Set([1, 2, 2, 3]);
let map = new Map();
map.set("name", "Ankit");

These structures provide better performance and flexibility compared to objects and arrays.


Advantages of ES6

  1. Cleaner and more readable syntax

  2. Better variable scoping and memory management

  3. Improved modular programming

  4. Easier asynchronous handling

  5. Better support for large applications

  6. Encourages modern JavaScript best practices

Fresher Interview Questions

 

1. What is ES6?

Answer:
ES6 stands for ECMAScript 6, also known as ECMAScript 2015. It is a major update to JavaScript that introduced new features to make the language more powerful, readable, and easier to write.

Why ES6 is important:

  • Cleaner syntax

  • Better handling of variables

  • Support for object-oriented programming

  • Modern features like arrow functions, promises, and modules


2. Difference between var, let, and const

var

  • Function scoped

  • Can be re-declared and re-assigned

  • Hoisted with undefined

let

  • Block scoped

  • Can be re-assigned but not re-declared

  • Safer than var

const

  • Block scoped

  • Cannot be re-assigned or re-declared

  • Used for constant values

Example:

var a = 10;
let b = 20;
const c = 30;

3. What is Block Scope?

Answer:
A variable declared inside { } using let or const is only accessible within that block.

Example:

{
  let x = 5;
}
console.log(x); // Error

4. What are Arrow Functions?

Answer:
Arrow functions provide a shorter syntax for writing functions and do not have their own this.

Syntax:

const add = (a, b) => a + b;

Advantages:

  • Shorter code

  • No need to write return for single expressions

  • No own this


5. Difference between Normal Function and Arrow Function

Normal Function Arrow Function
Has its own this Does not have this
Uses function keyword Uses =>
Can be used as constructor Cannot be constructor

6. What is Template Literal?

Answer:
Template literals allow string interpolation using backticks ( ).

Example:

let name = "Yash";
console.log(`Hello ${name}`);

Benefits:

  • Easy variable insertion

  • Multi-line strings


7. What is Destructuring?

Answer:
Destructuring allows unpacking values from arrays or objects into variables.

Array Destructuring:

let [a, b] = [10, 20];

Object Destructuring:

let {name, age} = {name: "Rahul", age: 25};

8. What is Default Parameter?

Answer:
Default parameters allow function parameters to have default values.

Example:

function greet(name = "Guest") {
  return `Hello ${name}`;
}

9. What is Spread Operator (...)?

Answer:
The spread operator expands elements of arrays or objects.

Example:

let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4];

10. What is Rest Parameter?

Answer:
Rest parameter collects multiple arguments into an array.

Example:

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b);
}

11. Difference between Spread and Rest

Spread Rest
Expands values Collects values
Used in function calls Used in parameters

12. What are Modules in ES6?

Answer:
Modules allow splitting code into multiple files.

Export:

export const name = "ES6";

Import:

import { name } from "./file.js";

13. What are Classes in ES6?

Answer:
Classes are templates for creating objects.

Example:

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log("Hello " + this.name);
  }
}

14. What is Constructor?

Answer:
A constructor is a special method that runs automatically when an object is created from a class.


15. What is Inheritance in ES6?

Answer:
Inheritance allows one class to use properties of another class using extends.

Example:

class Student extends Person {
  constructor(name, roll) {
    super(name);
    this.roll = roll;
  }
}

16. What is super Keyword?

Answer:
super is used to call the parent class constructor or methods.


17. What are Promises?

Answer:
Promises handle asynchronous operations.

States:

  • Pending

  • Fulfilled

  • Rejected

Example:

let promise = new Promise((resolve, reject) => {
  resolve("Success");
});

18. What is async and await?

Answer:
They make asynchronous code look synchronous.

Example:

async function fetchData() {
  let result = await fetch(url);
}

19. What is for...of Loop?

Answer:
Used to iterate over arrays and strings.

for (let val of [1,2,3]) {
  console.log(val);
}

20. What is Map?

Answer:
Map stores key-value pairs and allows any data type as key.

let map = new Map();
map.set("name", "ES6");

21. What is Set?

Answer:
Set stores unique values only.

let set = new Set([1,2,2,3]);

22. What is Hoisting in ES6?

Answer:

  • var is hoisted

  • let and const are hoisted but not initialized (Temporal Dead Zone)


23. What is Temporal Dead Zone?

Answer:
The time between variable declaration and initialization where it cannot be accessed.


24. What is Symbol?

Answer:
A primitive data type used to create unique identifiers.

let id = Symbol("id");

25. Why ES6 is better than ES5?

Answer:

  • Cleaner syntax

  • Less boilerplate code

  • Better scope management

  • Supports modern development


26. What is Object.assign() in ES6?

Answer:
Object.assign() is used to copy properties from one or more source objects to a target object.

Example:

let obj1 = { a: 1 };
let obj2 = { b: 2 };

let result = Object.assign({}, obj1, obj2);
console.log(result); // { a:1, b:2 }

Use case:

  • Cloning objects

  • Merging multiple objects


27. What is Enhanced Object Literal in ES6?

Answer:
ES6 provides shorter syntax when creating objects.

Example:

let name = "Yash";
let age = 25;

let user = { name, age };

Benefits:

  • Less code

  • Better readability


28. What is Object.freeze()?

Answer:
Object.freeze() prevents modification of an object.

Example:

const user = { name: "Rahul" };
Object.freeze(user);
user.name = "Amit"; // Not allowed

29. What is Object.seal()?

Answer:
Object.seal() allows modifying existing properties but prevents adding or deleting properties.


30. Difference between freeze and seal

Feature freeze seal
Modify value ❌ βœ…
Add property ❌ ❌
Delete property ❌ ❌

31. What is find() method in ES6?

Answer:
find() returns the first element that satisfies a condition.

Example:

let nums = [10, 20, 30];
let result = nums.find(n => n > 15);
console.log(result); // 20

32. What is findIndex()?

Answer:
Returns the index of the first matching element.

nums.findIndex(n => n > 15); // 1

33. What is includes() method?

Answer:
Checks whether an array or string contains a value.

[1,2,3].includes(2); // true

34. What is Array.from()?

Answer:
Converts array-like or iterable objects into arrays.

Array.from("HELLO"); // ['H','E','L','L','O']

35. What is Array.of()?

Answer:
Creates an array from arguments.

Array.of(1,2,3); // [1,2,3]

36. Difference between Array.from() and Array.of()

Array.from Array.of
Converts iterable Creates array
Accepts mapping function Simple creation

37. What is this behavior in Arrow Functions?

Answer:
Arrow functions do not have their own this. They inherit this from the parent scope.

Example:

function test() {
  this.name = "JS";
  setTimeout(() => {
    console.log(this.name);
  }, 1000);
}

38. What is for...in vs for...of?

for...in for...of
Iterates keys Iterates values
Used for objects Used for arrays

39. What are Generators in ES6?

Answer:
Generators are functions that can pause and resume execution.

Example:

function* gen() {
  yield 1;
  yield 2;
}

40. What is yield keyword?

Answer:
yield pauses a generator function and returns a value.


41. What is WeakMap?

Answer:
WeakMap stores objects as keys only and allows garbage collection.


42. Difference between Map and WeakMap

Map WeakMap
Any key type Only objects
Iterable Not iterable

43. What is WeakSet?

Answer:
Stores weakly referenced objects only.


44. What is Tail Call Optimization?

Answer:
An optimization where recursive calls reuse stack frames (supported in strict mode).


45. What is Number.isNaN()?

Answer:
Checks if the value is truly NaN.

Number.isNaN("abc"); // false

46. What is Number.isInteger()?

Answer:
Checks if value is an integer.

Number.isInteger(10); // true

47. What is Math.trunc()?

Answer:
Removes decimal part.

Math.trunc(4.9); // 4

48. What is Math.sign()?

Answer:
Returns:

  • 1 for positive

  • -1 for negative

  • 0 for zero


49. What is String.startsWith()?

"Hello".startsWith("He"); // true

50. What is String.endsWith()?

"Hello".endsWith("lo"); // true

51. What is String.repeat()?

"Hi".repeat(3); // HiHiHi

52. What is Object.is()?

Answer:
Compares two values strictly (better than === in some cases).


53. What is Proxy in ES6?

Answer:
Proxy allows custom behavior for object operations.

let p = new Proxy({}, {
  get(target, prop) {
    return prop in target ? target[prop] : "Not Found";
  }
});

54. What is Reflect?

Answer:
Provides methods for object operations (used with Proxy).


55. What is Default Export vs Named Export?

Default Export Named Export
One per file Multiple allowed
No braces Uses braces

56. What is Promise.all()?

Answer:
Executes multiple promises in parallel.


57. What is Promise.race()?

Answer:
Returns first resolved or rejected promise.


58. What is Promise.catch()?

Answer:
Handles errors in promises.


59. What is finally() in Promise?

Answer:
Executes code regardless of success or failure.

 

Experienced Interview Questions

 

1. How does ES6 improve JavaScript architecture?

Answer:
ES6 introduces features that enable modular, scalable, and maintainable code.

Key architectural improvements:

  • Modules (import/export)

  • Block scoping (let, const)

  • Classes & inheritance

  • Promises & async flow

  • Immutable patterns (spread, destructuring)

πŸ‘‰ ES6 helps move JS from script-based programming to application-level development.


2. Explain Temporal Dead Zone (TDZ) with real use-case

Answer:
TDZ is the time between entering scope and variable declaration where let and const cannot be accessed.

console.log(a); // ReferenceError
let a = 10;

Why TDZ exists:

  • Prevents usage of variables before declaration

  • Avoids bugs caused by hoisting

πŸ‘‰ TDZ forces clean coding discipline, unlike var.


3. How does this behave differently in arrow functions?

Answer:
Arrow functions lexically bind this from the parent scope.

Real-world example:

class Counter {
  constructor() {
    this.count = 0;
  }

  start() {
    setInterval(() => {
      this.count++;
    }, 1000);
  }
}

βœ” No need for bind(this)
βœ” Avoids common bugs in callbacks


4. Why should const be preferred over let?

Answer:
const ensures immutability of reference, not value.

const user = { name: "A" };
user.name = "B"; // Allowed

Benefits:

  • Prevents accidental reassignment

  • Improves code readability

  • Helps reasoning about state

πŸ‘‰ Industry standard: use const by default, let only when needed


5. Explain shallow copy vs deep copy using ES6

Shallow Copy (Spread):

const obj2 = { ...obj1 };

Problem:

  • Nested objects still share reference

Deep Copy:

const deep = JSON.parse(JSON.stringify(obj));

OR using libraries (recommended for production):

  • lodash cloneDeep


6. Explain Destructuring with real use-case

Answer:
Destructuring is heavily used in:

  • API responses

  • Function parameters

  • Redux / Angular / React props

function getUser({ name, role }) {
  console.log(name, role);
}

βœ” Cleaner code
βœ” Avoids repetitive object access


7. What are ES6 Modules and how do they differ from CommonJS?

ES6 Modules CommonJS
import/export require/module.exports
Static Dynamic
Tree-shakable Not tree-shakable
Browser supported Node.js

πŸ‘‰ ES6 modules enable better bundling and performance


8. What is Tree Shaking?

Answer:
Tree shaking removes unused code during build time.

import { add } from './math';

Only add is bundled, unused exports removed.

βœ” Smaller bundle size
βœ” Faster load time


9. Explain Promises internally

Answer:
A Promise is an object that represents future completion.

States:

  • Pending

  • Fulfilled

  • Rejected

new Promise((resolve, reject) => {
  resolve(data);
});

Promises use microtask queue, which executes before normal callbacks.


10. Difference between Promise.all, allSettled, race, any

Method Behavior
all Fails if any fails
allSettled Waits for all
race First settled
any First success

11. Why async/await is better than promises chaining?

Answer:

  • Cleaner syntax

  • Better error handling

  • Easier debugging

  • Synchronous-like flow

try {
  const data = await fetchData();
} catch (err) {
  console.log(err);
}

12. Explain Event Loop + Promise execution order

Answer:
Order of execution:

  1. Call stack

  2. Microtask queue (Promises)

  3. Macrotask queue (setTimeout)

setTimeout(() => console.log("timeout"));
Promise.resolve().then(() => console.log("promise"));

Output:

promise
timeout

13. What is Rest vs Spread with real scenario?

Spread:

const updated = { ...user, role: "admin" };

Rest:

function log(...args) {
  console.log(args);
}

πŸ‘‰ Used heavily in reducers, APIs, and reusable utilities.


14. Explain Map vs Object in real apps

Map Advantages:

  • Any key type

  • Maintains order

  • Faster iteration

Use Map when:

  • Dynamic keys

  • Frequent add/remove

  • Performance matters


15. Explain Set usage in real-world

Answer:
Used to remove duplicates.

const uniqueUsers = [...new Set(users)];

Common use:

  • Tags

  • Permissions

  • Unique IDs


16. Explain Proxy with use-case

Answer:
Proxy intercepts object operations.

const user = new Proxy({}, {
  get(target, prop) {
    if (!(prop in target)) {
      throw new Error("Invalid property");
    }
    return target[prop];
  }
});

Use cases:

  • Validation

  • Logging

  • Security

  • Reactive frameworks (Vue)


17. What is Reflect and why use it?

Answer:
Reflect provides standard methods for object operations.

Reflect.get(obj, prop);

Benefits:

  • Cleaner error handling

  • Works well with Proxy


18. Explain Symbols with practical use

Answer:
Symbols create hidden, unique keys.

const ID = Symbol("id");
user[ID] = 101;

Used in:

  • Libraries

  • Framework internals

  • Preventing key collision


19. How does ES6 help in immutability?

Tools:

  • Spread operator

  • Object.freeze

  • Destructuring

const newState = { ...state, count: state.count + 1 };

πŸ‘‰ Crucial for React, Redux, Angular signals.


20. What problem does ES6 solve compared to ES5?

Answer:
ES6 solves major ES5 issues like:

  • Global scope pollution

  • Callback hell

  • Poor modularity

  • Hard-to-maintain prototype syntax

How ES6 fixes this:

  • let / const → block scoping

  • Promises / async-await → clean async code

  • Modules → structured architecture

  • Classes → readable OOP

πŸ‘‰ ES6 enables enterprise-scale JavaScript applications.


21. Explain block scope with a real bug example

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Output:

3 3 3

Fix using ES6:

for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

Output:

0 1 2

πŸ‘‰ let creates a new scope per iteration.


22. How does const work internally?

Answer:
const prevents reassignment, not mutation.

const obj = { a: 1 };
obj.a = 2; // allowed
obj = {}; // ❌ error

πŸ‘‰ Reference is constant, value may change.


23. Explain Temporal Dead Zone (TDZ) with reason

console.log(x); // ReferenceError
let x = 10;

Why TDZ exists:

  • Prevents accidental usage before declaration

  • Forces predictable execution

πŸ‘‰ TDZ is a design decision, not a bug.


24. Arrow function vs normal function (real scenario)

function Timer() {
  this.time = 0;
  setInterval(() => {
    this.time++;
  }, 1000);
}

βœ” Arrow function inherits this
❌ Normal function would require .bind(this)


25. When NOT to use arrow functions?

Answer:
Avoid arrow functions:

  • As object methods

  • As constructors

  • When dynamic this is required

const obj = {
  show: () => console.log(this)
};

πŸ‘‰ this will be incorrect.


26. Explain destructuring in function parameters

function login({ email, password }) {
  // use email & password
}

Benefits:

  • Clean code

  • Avoids repetitive access

  • Safer API contracts

Used heavily in:

  • React props

  • API handlers

  • Redux reducers


27. Explain default parameters execution timing

function calc(a, b = a * 2) {
  return b;
}
calc(5); // 10

πŸ‘‰ Default parameters are evaluated at runtime, not at definition.


28. Spread operator in state management

const newState = {
  ...state,
  count: state.count + 1
};

Why important:

  • Immutability

  • Change detection

  • Predictable state

Used in React, Angular, Redux.


29. Rest operator vs arguments object

function sum(...nums) {
  return nums.reduce((a, b) => a + b);
}

Advantages over arguments:

  • Real array

  • Works with arrow functions

  • Cleaner syntax


30. Explain shallow copy problem in ES6

const a = { x: { y: 1 } };
const b = { ...a };
b.x.y = 2;

Result:
Both a and b change.

πŸ‘‰ Spread creates shallow copy only.


31. How do ES6 modules improve performance?

Answer:

  • Static imports

  • Tree-shaking

  • Smaller bundles

  • Better dependency analysis

import { add } from './math';

Unused code is removed at build time.


32. Difference between default export and named export

Default Export Named Export
One per file Multiple
No braces Uses braces
Any name Exact name

33. Explain Promise chaining best practice

❌ Wrong:

fetchData().then(() => {
  fetchMore();
});

βœ” Correct:

fetchData().then(() => fetchMore());

πŸ‘‰ Always return promises in .then().


34. Explain Promise microtask queue

setTimeout(() => console.log(1));
Promise.resolve().then(() => console.log(2));
console.log(3);

Output:

3
2
1

πŸ‘‰ Promises execute before timers.


35. Why async/await improves debugging?

Answer:

  • Linear flow

  • Stack traces readable

  • Easier error handling

try {
  await apiCall();
} catch (e) {
  handleError(e);
}

36. Explain Map over Object in real systems

Use Map when:

  • Keys are dynamic

  • Frequent add/remove

  • Order matters

const cache = new Map();
cache.set(userId, data);

37. Set usage in production systems

const uniqueIds = [...new Set(ids)];

Used in:

  • Permission systems

  • Deduplication

  • Feature flags


38. Explain WeakMap real use-case

Answer:
Used for private data storage.

const privateData = new WeakMap();

Garbage collected automatically → prevents memory leaks.


39. What are common ES6 mistakes made by experienced developers?

Answer:
Even experienced developers often make these ES6 mistakes:

  • Overusing arrow functions where this is required

  • Mutating objects while assuming immutability

  • Forgetting to return promises in .then()

  • Using spread operator inside loops (performance issue)

  • Misunderstanding shallow vs deep copy

πŸ‘‰ Interviewers look for awareness of trade-offs, not just syntax.


40. Explain shallow copy vs deep copy in real applications

Shallow Copy

const obj2 = { ...obj1 };
  • Only first level copied

  • Nested references remain same

Deep Copy

const deep = JSON.parse(JSON.stringify(obj));

Real-world impact:
In state management (React/Redux), shallow copy is enough only if structure is flat.


41. Why is immutability important in ES6-based frameworks?

Answer:
Immutability helps:

  • Detect changes easily

  • Prevent side effects

  • Improve performance via reference checks

const newState = { ...state, count: state.count + 1 };

Used heavily in:

  • React

  • Angular (OnPush)

  • Redux / NgRx


42. Explain how ES6 modules are statically analyzed

Answer:
ES6 imports are resolved at compile time, not runtime.

import { sum } from './math';

Benefits:

  • Tree-shaking

  • Early error detection

  • Better bundling


43. Why CommonJS cannot be tree-shaken effectively?

Answer:
CommonJS uses dynamic require():

const lib = require('./lib');

Bundlers can’t know what’s used → all code included.


44. Explain Promise internal working

Answer:
Promise has:

  • State

  • Result

  • Callbacks queue

Promises run callbacks in microtask queue, which has higher priority than macrotasks.


45. Difference between .then() and await

.then() await
Callback-based Synchronous style
Harder to debug Cleaner stack trace
Nested possible Linear flow

46. Explain Promise error bubbling

Promise.resolve()
  .then(() => {
    throw new Error("Failed");
  })
  .then(() => {})
  .catch(err => console.log(err.message));

Errors propagate until caught.


47. When to use Promise.allSettled()?

Answer:
When partial success is acceptable.

Example:

  • Dashboard widgets loading

  • Multiple API calls where some may fail


48. Event loop tricky output (interview favorite)

console.log(1);

setTimeout(() => console.log(2), 0);

Promise.resolve().then(() => console.log(3));

console.log(4);

Output:

1
4
3
2

49. What is microtask starvation?

Answer:
Continuous promise resolution can delay timers.

function loop() {
  Promise.resolve().then(loop);
}

πŸ‘‰ Timers may never execute.


50. Explain Map vs Object in caching systems

Answer:
Map is preferred because:

  • Keys can be objects

  • Maintains insertion order

  • Faster iteration

const cache = new Map();
cache.set(user, data);

51. How does WeakMap prevent memory leaks?

Answer:
WeakMap keys are weakly referenced.

When key object is garbage collected, value is removed automatically.

Used in:

  • DOM metadata

  • Private properties


52. Explain Set-based deduplication pattern

const uniqueUsers = [...new Set(users)];

Used in:

  • Permissions

  • Tag systems

  • User lists


53. Explain Symbol with collision prevention example

const id = Symbol("id");
obj[id] = 1;

Symbols avoid conflicts with user-defined keys.


54. Explain Symbol.iterator and custom iteration

const collection = {
  *[Symbol.iterator]() {
    yield 1;
    yield 2;
  }
};

Allows for...of iteration.


55. Generator vs Async function (deep comparison)

Generator Async
Pausable Promise-based
Manual iteration Automatic
yield await

Async functions internally use promises.


56. Explain Object.freeze() limitations

Answer:
Freeze is shallow.

Object.freeze(obj);
obj.inner.value = 10; // Allowed

For deep freeze, recursion is needed.


57. Explain ES6 best practices in large projects

  • Use const by default

  • Avoid deep cloning

  • Prefer Map/Set

  • Keep async code flat

  • Avoid shared mutable state