Introduction & Syntax
ES6 Features · Study material
ES6 – officially ECMAScript 2015 – was the biggest update in JavaScript's history: let and const, arrow functions, template literals, destructuring, default and rest parameters, spread, classes, modules, Map and Set, Symbol, iterators and generators, and Promises. Since then a smaller update has arrived every year (ES2016, ES2017 …). Interviews ask "what are the ES6 features?" and then dig into classes and inheritance, private fields, Map vs object, iterables and generators. This topic covers those features in depth; destructuring, spread/rest and arrow functions have their own topics. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Classes
A class is cleaner syntax over JavaScript's prototypes. The constructor initialises each object created with new; methods are shared through the prototype; get/set define accessors; static members belong to the class itself; class fields (count = 0) are created on each instance; private fields (#balance) can be used only inside the class body. Classes are always strict, are not hoisted like functions (they stay in the TDZ), and must be called with new. typeof a class is "function".
class Account {
#balance = 0; // private field: only code inside the class can read it
static count = 0; // static field: belongs to the class, not to each object
constructor(owner) {
this.owner = owner;
Account.count++;
}
deposit(amount) {
this.#balance += amount;
return this; // returning this allows chaining
}
get balance() { return this.#balance; }
}
const a = new Account("Asha").deposit(500).deposit(250);
console.log(a.owner, a.balance, Account.count, typeof Account);
console.log(Object.keys(a), "#balance" in a); // private fields are not properties
Asha 750 1 function [ 'owner' ] false
Inheritance with extends and super
class Circle extends Shape makes Circle's prototype inherit from Shape's. In a derived class constructor, super(...) must be called before this is used (and if you write no constructor, one that passes all arguments to super is created for you). A method with the same name overrides the parent's; super.method() calls the parent version. instanceof checks the whole chain.
class Shape {
constructor(name) { this.name = name; }
area() { return 0; }
describe() { return `${this.name} with area ${this.area().toFixed(2)}`; }
}
class Circle extends Shape {
constructor(r) {
super("Circle"); // must run before this is used
this.r = r;
}
area() { return Math.PI * this.r ** 2; } // overrides Shape's area
}
class Square extends Shape {
constructor(s) { super("Square"); this.s = s; }
area() { return this.s ** 2; }
}
for (const shape of [new Circle(1), new Square(3)]) console.log(shape.describe());
console.log(new Circle(2) instanceof Shape, Object.getPrototypeOf(Circle) === Shape);
Circle with area 3.14 Square with area 9.00 true true
Map and Set
| Object | Map | |
|---|---|---|
| Keys | strings and symbols | any value (objects, numbers, functions) |
| Size | Object.keys(o).length | map.size |
| Order | integer keys first, then insertion | insertion order |
| Iterable | no (use Object.entries) | yes |
| Inherited keys | yes (toString …) | no |
A Set stores unique values (using SameValueZero: NaN equals NaN, objects are compared by reference) – the standard way to remove duplicates: [...new Set(arr)]. WeakMap and WeakSet hold objects weakly: they cannot be iterated and have no size, and entries vanish when the key object is no longer used.
// Map: key → value, any key type, remembers insertion order
const visits = new Map();
for (const page of ["/home", "/js", "/home", "/python", "/home"]) {
visits.set(page, (visits.get(page) ?? 0) + 1);
}
console.log(visits.size, visits.get("/home"), [...visits.keys()]);
// Set: unique values, insertion order
const unique = new Set(["js", "css", "js"]);
unique.add("html").add("css");
console.log(unique.size, unique.has("css"), [...unique]);
3 3 [ '/home', '/js', '/python' ] 3 true [ 'js', 'css', 'html' ]
Symbols and the iteration protocol
Symbol() creates a unique value, often used as a property key that cannot collide with others; symbol keys are skipped by Object.keys and JSON.stringify. Well-known symbols customise language behaviour – the most important is Symbol.iterator: an object is iterable if obj[Symbol.iterator]() returns an iterator, an object with a next() method returning { value, done }. for…of, spread, destructuring, Array.from, Map, Set and Promise.all all use this protocol.
// Any object with a [Symbol.iterator]() method returning { next() } works with for…of and spread
const range = {
from: 1,
to: 4,
[Symbol.iterator]() {
let current = this.from;
const last = this.to;
return {
next: () => (current <= last ? { value: current++, done: false } : { value: undefined, done: true }),
};
},
};
console.log([...range], Math.max(...range));
for (const n of range) if (n % 2 === 0) console.log("even", n);
[ 1, 2, 3, 4 ] 4 even 2 even 4
Generators
A generator function (function*) returns a generator object, which is both an iterator and an iterable. Calling it runs nothing; each next() runs the body until the next yield, returns { value, done: false } and pauses. A return (or the end of the body) finishes it with done: true – and for…of and spread ignore the returned value. yield* delegates to another iterable. Because values are produced on demand, generators can describe infinite sequences.
// function* returns a generator: it runs until yield, pauses, and resumes on the next next()
function* idGenerator(prefix) {
let id = 1;
while (true) yield `${prefix}-${id++}`; // infinite is fine: values are produced on demand
}
const ids = idGenerator("ORD");
console.log(ids.next().value, ids.next().value, ids.next());
function* take(iterable, n) {
for (const x of iterable) {
if (n-- <= 0) return;
yield x;
}
}
console.log([...take(idGenerator("TKT"), 3)]);
ORD-1 ORD-2 { value: 'ORD-3', done: false }
[ 'TKT-1', 'TKT-2', 'TKT-3' ]Enhanced object literals and the rest of ES6
ES6 also brought shorthand properties, computed keys and method shorthand in object literals, default parameters, rest/spread and destructuring – often used together, as below.
const name = "Asha", role = "admin", key = "lastLogin";
// ES6 object literals: shorthand properties, computed keys, method shorthand
const user = { name, role, [key]: "2026-11-30", greet() { return `Hi ${this.name}`; } };
const { greet, ...data } = user; // destructuring + rest
const withDefaults = ({ theme = "light", ...rest } = {}) => ({ theme, ...rest }); // defaults + spread
console.log(data, user.greet());
console.log(withDefaults({ lang: "hi" }), withDefaults());
{ name: 'Asha', role: 'admin', lastLogin: '2026-11-30' } Hi Asha
{ theme: 'light', lang: 'hi' } { theme: 'light' }After ES6: a yearly release
| Version | Notable additions |
|---|---|
| ES2016 | **, Array.prototype.includes |
| ES2017 | async/await, Object.entries/values, padStart/padEnd |
| ES2018 | object rest/spread, Promise.finally, named regex groups |
| ES2019 | flat, flatMap, Object.fromEntries, optional catch binding |
| ES2020 | ?., ??, BigInt, Promise.allSettled, globalThis, dynamic import() |
| ES2021 | replaceAll, ||= &&= ??=, numeric separators, Promise.any |
| ES2022 | class fields, #private, static blocks, at(), Object.hasOwn, top-level await |
| ES2023 | findLast, toSorted, toReversed, with |
console.log(2 ** 10, [1, 2, NaN].includes(NaN)); // ES2016
console.log(Object.entries({ a: 1 }), "5".padStart(3, "0")); // ES2017
console.log([1, [2, [3]]].flat(Infinity), Object.fromEntries([["x", 1]])); // ES2019
console.log(null ?? "default", undefined?.x, 2n ** 64n); // ES2020
console.log(1_000_000, [3, 1, 2].at(-1)); // ES2021, ES2022
1024 true
[ [ 'a', 1 ] ] 005
[ 1, 2, 3 ] { x: 1 }
default undefined 18446744073709551616n
1000000 2Common mistakes
- Calling a class without new – TypeError.
- Using this before super() in a derived constructor – ReferenceError.
- Treating a Map like an object – map["key"] = 1 sets a property, not an entry; use set/get.
- Expecting a Set to remove duplicate objects – objects are compared by reference.
- Iterating a generator twice – once it is done, it stays done.
- Spreading a class instance – own fields are copied, prototype methods are lost.
- import in a non-module script – SyntaxError; use type="module" or .mjs.
Key points to remember
- ES6 = ES2015; new features arrive every year since.
- Classes: constructor, methods on the prototype, static, fields, #private, extends/super.
- Classes are strict, not callable without new, and not hoisted like functions.
- Map: any key type, size, insertion order; Set: unique values.
- Iterable = has [Symbol.iterator]() returning { next() }.
- Generators pause at yield and produce values lazily.
- Modules: import/export, strict mode, their own scope.
Frequently asked questions
Are JavaScript classes like Java classes?
They look similar, but they are built on prototypes: methods live on Class.prototype, and objects inherit from it at run time. There is no overloading, and privacy uses # fields.
When should I use a Map instead of an object?
For dictionaries whose keys are not known in advance, are not strings, or change often, and when you need the size or reliable insertion order. Use objects for records with fixed fields.
Do I still need generators now that async/await exists?
Yes, for lazy sequences, custom iterables and pipelines over large data. async/await is itself built on the same idea of pausing a function.
Where can I learn more?
Read JavaScript Classes, Map and Set, Generators and Modules in the JavaScript tutorial, then practise with the exercises below.