LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 14 of 25

ES6 Features Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

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

Output

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);

Output

Circle with area 3.14
Square with area 9.00
true true

Map and Set

ObjectMap
Keysstrings and symbolsany value (objects, numbers, functions)
SizeObject.keys(o).lengthmap.size
Orderinteger keys first, then insertioninsertion order
Iterableno (use Object.entries)yes
Inherited keysyes (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]);

Output

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);

Output

[ 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)]);

Output

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());

Output

{ name: 'Asha', role: 'admin', lastLogin: '2026-11-30' } Hi Asha
{ theme: 'light', lang: 'hi' } { theme: 'light' }

After ES6: a yearly release

VersionNotable additions
ES2016**, Array.prototype.includes
ES2017async/await, Object.entries/values, padStart/padEnd
ES2018object rest/spread, Promise.finally, named regex groups
ES2019flat, flatMap, Object.fromEntries, optional catch binding
ES2020?., ??, BigInt, Promise.allSettled, globalThis, dynamic import()
ES2021replaceAll, ||= &&= ??=, numeric separators, Promise.any
ES2022class fields, #private, static blocks, at(), Object.hasOwn, top-level await
ES2023findLast, 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

Output

1024 true
[ [ 'a', 1 ] ] 005
[ 1, 2, 3 ] { x: 1 }
default undefined 18446744073709551616n
1000000 2

Common 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.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links