0% found this document useful (0 votes)
3 views14 pages

ES6 Interview Prep Guide - Key Features Explained

The document is an ES6 interview preparation guide that explains key features such as let and const, arrow functions, template literals, default parameters, rest and spread operators, destructuring, enhanced object literals, classes, modules, promises, iterators, generators, Map and Set, Symbols, block scope, and new string and number methods. Each feature is described with examples and use cases to illustrate their benefits and applications in JavaScript. The guide aims to provide a comprehensive understanding of ES6 for interview preparation.

Uploaded by

mehedy.cuet.cse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

ES6 Interview Prep Guide - Key Features Explained

The document is an ES6 interview preparation guide that explains key features such as let and const, arrow functions, template literals, default parameters, rest and spread operators, destructuring, enhanced object literals, classes, modules, promises, iterators, generators, Map and Set, Symbols, block scope, and new string and number methods. Each feature is described with examples and use cases to illustrate their benefits and applications in JavaScript. The guide aims to provide a comprehensive understanding of ES6 for interview preparation.

Uploaded by

mehedy.cuet.cse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ES6 Interview Prep Guide: Key Features Explained

let and const


Q: What are let and const in ES6, and how do they differ from var ?
ES6 introduced let and const for variable declaration. Unlike var , they are block-scoped, meaning
they only exist inside the closest {...} block 1 . A let variable can be reassigned, but const creates
a constant binding that cannot be reassigned after its initial definition 2 3 . In contrast, var is function-
scoped and allows re-declaration, which can lead to bugs. For example:

if (true) {
let x = 1;
const y = 2;
var z = 3;
}
[Link](typeof x); // "undefined" (x is block-scoped)
[Link](typeof y); // "undefined" (y is block-scoped)
[Link](z); // 3 (z is function/global-scoped)

- Use cases: Use const for values that shouldn’t change (like configuration or fixed data) and let for
loop counters or variables that will be reassigned. This prevents accidental overwrites and makes code
clearer 3 .

Arrow Functions
Q: How do arrow functions work, and why use them?
Arrow functions provide a concise syntax for writing functions. They use the => arrow and implicitly return
expressions when used without braces. Critically, arrow functions do not have their own this or
arguments – they inherit this from the surrounding context 4 . This is helpful in callbacks or class
methods. For example:

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


const nums = [1,2,3];
const doubled = [Link](n => n * 2);
[Link](add(2,3)); // 5
[Link](doubled); // [2, 4, 6]

- Benefits: Shorter syntax (no function keyword or return needed for single expressions) and lexical
this binding, which avoids common pitfalls in callbacks 4 . Use arrows for simple one-line functions
(e.g. array iteration) and to preserve this from the outer scope.

1
Template Literals
Q: What are template literals and how do they help with strings?
Template literals use backticks <code>`...`</code> to define strings, allowing embedded expressions and
multi-line text 5 . You can interpolate variables or any JS expression with ${…} . For example:

const user = { name: "Alice", age: 30 };


const greeting = `Hello, ${[Link]}! You are ${[Link]} years old.`;
const multiline = `Items:
- Apples
- Oranges`;
[Link](greeting); // Hello, Alice! You are 30 years old.
[Link](multiline);
// Items:
// - Apples
// - Oranges

- Use cases: Building dynamic strings (like HTML templates or messages) without cumbersome
concatenation. Template literals make code readable and support multi-line text and string interpolation
5 .

Default Parameters
Q: How do default parameters work in ES6 functions?
Default parameters let you specify a default value in a function signature if no argument (or undefined )
is passed. This avoids manual checks inside the function. For example:

function greet(name = "Guest", greeting = "Hello") {


[Link](`${greeting}, ${name}!`);
}
greet("Bob"); // Hello, Bob!
greet(); // Hello, Guest!
greet(undefined, "Hi"); // Hi, Guest!

MDN notes that default parameters “allow named parameters to be initialized with default values if no value
or undefined is passed” 6 .
- Use cases: Simplify functions with optional arguments. Instead of checking
if (name === undefined) name = "Guest" , just set function(name = "Guest") .

Rest and Spread Operators


Q: What are the rest and spread ... operators in ES6?
The ... syntax serves two purposes. As a rest parameter in function definitions, it collects all remaining
arguments into an array 7 . As a spread operator, it expands (spreads) an iterable (like an array) into

2
individual elements 8 . Examples:

// Rest parameter: collect args into array


function sum(...numbers) {
return [Link]((a, b) => a + b, 0);
}
[Link](sum(1,2,3,4)); // 10

// Spread operator: expand array into elements


const nums = [5,6,7];
[Link](sum(...nums)); // 18 (calls sum(5,6,7))

// Spread in array literals (e.g., copying/merging)


const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
[Link](arr2); // [1, 2, 3, 4]

// Spread in object literals (ES2018+)


const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 };
[Link](obj2); // {a:1, b:2, c:3}

- Benefits: Rest parameters make functions variadic (able to take any number of args) 7 . Spread syntax
simplifies array manipulation and merging. For example, use [Link](...arr) or easily concatenate
arrays/objects without loops 8 .

Destructuring (Arrays and Objects)


Q: What is destructuring assignment in ES6?
Destructuring lets you unpack values from arrays or properties from objects into variables in a single
statement 9 . It makes code concise and readable. For example:

// Array destructuring
const rgb = [255, 200, 100];
const [r, g, b] = rgb;
[Link](r, g, b); // 255 200 100

// Object destructuring
const user = { name: "Alice", age: 30, country: "USA" };
const { name, country } = user;
[Link](name, country); // Alice USA

// Nested and default values

3
const [first = 0, second = 0] = [10];
[Link](first, second); // 10 0

- Use cases: Easily extract data from arrays/objects. E.g., unpack function return values: const [min,
max] = getMinMax(array) . Also useful to swap variables ( [a, b] = [b, a] ) and to pass object fields
as function params. Destructuring reduces boilerplate code for common assignments 9 .

Enhanced Object Literals


Q: What are enhanced object literal features in ES6?
ES6 allows shorter syntax for defining object properties and methods, making objects more concise:
- Property shorthand: If variable name and key name are the same, just write it once. E.g., { a, b }
instead of {a: a, b: b} 10 .
- Method shorthand: Drop the function keyword for methods. E.g., { greet() { ... } } instead
of { greet: function() { ... } } 11 .
- Example:

const name = "Alice", age = 30;


const person = { name, age, // shorthand properties
greet() { [Link]("Hi " + [Link]); } // shorthand method
};
[Link](); // Hi Alice

- Use cases: Cleaner object definitions, especially when building objects from local variables or defining
methods. These features reduce redundancy and improve readability 11 .

Classes
Q: How do ES6 classes work compared to constructor functions?
ES6 class syntax is sugar over prototype-based inheritance 12 . A class defines a constructor and
methods inside its body. For example:

class Animal {
constructor(name) {
[Link] = name;
}
speak() {
[Link](`${[Link]} makes a noise.`);
}
}

class Dog extends Animal {


speak() {
[Link]();

4
[Link](`${[Link]} barks.`);
}
}

const d = new Dog("Rex");


[Link]();
// Output:
// Rex makes a noise.
// Rex barks.

According to MDN, “Classes are a template for creating objects. They encapsulate data with code…” and are
built on prototypes 12 . Key points: class declarations are not hoisted, and methods defined in the class
body become prototype methods.
- Use cases: Organizing code with clear OOP style. Use class for modeling real-world entities and
inheritance (using extends and super() ). It’s more intuitive than manually setting up prototypes, while
maintaining prototype behavior under the hood 12 .

Modules (import/export)
Q: What are ES6 modules and how do import / export work?
ES6 modules allow splitting code into separate files (modules) with export and import syntax. You can
mark functions/variables in a file to be exported, and then import them elsewhere. For example:

// [Link] (module file)


export function add(a, b) { return a + b; }
export const PI = 3.14;

// [Link]
import { add, PI } from './[Link]';
[Link](add(2,3)); // 5
[Link](PI); // 3.14

// Default export
// module: [Link]
export default function log(msg) { [Link](msg); }

// [Link]
import log from './[Link]';
log("Hello");

Modules run in strict mode by default and only top-level import / export are allowed. As MDN explains,
complex projects need modules “for splitting JavaScript programs into separate modules that can be
imported when needed” 13 .
- Benefits: Better code organization and reuse, avoiding globals. Static structure enables build tools and

5
browsers to optimize loading (e.g. tree-shaking unused exports). Modules also let you rename imports and
combine multiple modules, improving maintainability 13 .

Promises
Q: What are Promises and why use them?
A Promise represents an asynchronous operation’s eventual result or failure 14 . Instead of callbacks, a
function can return a Promise that will resolve (success) or reject (error). You attach .then() and
.catch() handlers to consume it. For example:

function fetchData(url) {
return new Promise((resolve, reject) => {
fetch(url)
.then(response => [Link]())
.then(data => resolve(data))
.catch(err => reject(err));
});
}

fetchData('/api/data')
.then(data => [Link]('Got data:', data))
.catch(err => [Link]('Error:', err));

MDN defines Promise as an object representing “the eventual completion (or failure) of an asynchronous
operation and its resulting value” 14 .
- Use cases: Managing async tasks in sequence or parallel. Promises avoid “callback hell” by chaining. For
example, use [Link]() to wait for multiple requests. Built-in APIs like fetch() return Promises,
making code easier to read and error-handle than nested callbacks.

Iterators and for...of Loop


Q: What are iterators and how does for...of work?
An iterator is an object with a next() method that returns { value, done } 15 . It defines a sequence
of values and possibly a return value upon completion. Many built-ins (Array, String, Map, Set, etc.) are
iterable, meaning they implement [[Link]] and produce an iterator. The for...of loop
uses this to iterate over values 16 . For example:

const array = [10, 20, 30];


for (const num of array) {
[Link](num);
}
// Output: 10 20 30

const text = "hi";

6
for (const char of text) {
[Link](char);
}
// Output: 'h' 'i'

MDN notes that for...of loops over iterable values: arrays, strings, Maps, Sets, etc. 16 . Internally,
for...of calls the iterable’s iterator and repeatedly calls next() .
- Use cases: Simpler looping. Unlike for with index, for...of directly gives each value. It also works on
many iterable objects. Use it to loop through arrays, strings, sets, maps, or any custom iterable without
manual index management 16 15 .

Generators
Q: What are generator functions ( function* ) and yield ?
Generator functions are declared with function* and can pause execution with yield . Each time you
call a generator, it returns an iterator (generator object) that you can call next() on. On each next() ,
the function runs until the next yield , returning that value. The execution context is saved between
yields 17 . For example:

function* countUp() {
yield 1;
yield 2;
yield 3;
}
const gen = countUp();
[Link]([Link]().value); // 1
[Link]([Link]().value); // 2
[Link]([Link]().value); // 3

MDN explains that a generator “can be exited and later re-entered, with its context (variable bindings) saved
across re-entrances” 17 .
- Use cases: Lazy or potentially infinite sequences (like streaming data). Generators allow on-demand value
generation (e.g. iterating Fibonacci numbers without computing all at once). They’re also used in async
programming frameworks (though async/await is often built on generators).

Map and Set


Q: What are Map and Set in ES6?
Map and Set are new collection types. A Map is a collection of key-value pairs where keys can be any
type (including objects) 18 . It remembers insertion order and offers fast lookup. Example:

const map = new Map();


[Link]('a', 1);
[Link]({k: 2}, 2);

7
[Link]([Link]('a')); // 1
[Link]([Link]); // 2

A Set is a collection of unique values (no duplicates) of any type 19 . In a Set, each value can appear only
once. Example:

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


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

MDN notes: “Map holds key-value pairs…and any value may be used as a key or value.” 18 . And “Set lets you
store unique values of any type…” 19 .
- Benefits: Use Map when you need keys other than strings (e.g. object keys) or care about insertion order.
Use Set to easily enforce uniqueness (e.g. removing duplicates from an array). Both support easy
iteration ( for...of map yields [key,value] pairs, for...of set yields values) and useful methods
like .has , .delete , and size property.

Symbol
Q: What is a Symbol and how is it used?
Symbol is a new primitive type introduced in ES6. Each Symbol() call returns a unique value (even with
the same description), making it ideal for unique object keys 20 . For example:

const id1 = Symbol("id");


const id2 = Symbol("id");
[Link](id1 === id2); // false

const obj = {};


obj[id1] = 100;
[Link](obj[id1]); // 100

MDN explains: “Symbol is a built-in object whose constructor returns a symbol primitive … that’s guaranteed to
be unique. Symbols are often used to add unique property keys to an object that won’t collide with keys any other
code might add…” 20 .
- Use cases: Private or meta-properties. For instance, use Symbols as object keys to avoid naming conflicts
and ensure they don’t show up in normal property iteration. Libraries often use well-known symbols (like
[Link] or [Link] ) to implement custom behaviors without clashing with
normal property names 20 .

Block Scope
Q: What does block scope mean in ES6?
Block scope means a variable is only visible within the nearest {} (like an if block or loop). In ES6, let
and const are block-scoped, unlike var which is function-scoped. As MDN notes, let declares “block-

8
scoped local variables” 1 . Example:

{
let a = 10;
const b = 20;
}
[Link](typeof a, typeof b); // "undefined undefined"

- Benefits: Prevents variables from leaking out of blocks, avoiding unexpected interactions. E.g., using
let in a for loop creates a fresh binding each iteration. Block scope improves code safety by limiting
variable lifespan 1 .

String and Number Enhancements


Q: What new string and number methods were added in ES6?
ES6 added several convenient string and number utilities:
- String methods: startsWith() , endsWith() , and includes() make substring checks easier than
using indexOf or regex. E.g., "hello".startsWith("he") is true. GeeksforGeeks notes these
methods reduce reliance on RegExp . 21

- Number methods: [Link]() more accurately checks for NaN (won’t coerce non-numbers) and
[Link]() to test if a value is an integer. There are also [Link] / parseFloat
as aliases to global functions.

[Link]("world".includes("wor")); // true
[Link]("abc".endsWith("c")); // true
[Link]([Link](NaN)); // true
[Link]([Link](3.14)); // false

- Use cases: These methods simplify common checks: e.g. use .includes() instead of
[Link](sub) !== -1 . startsWith/endsWith improve readability. [Link] avoids
pitfalls of the global isNaN . Overall, they make code more expressive and concise.

[Link]()
Q: What does [Link]() do?
[Link](target, ...sources) copies enumerable properties from one or more source objects
to a target object 22 . It returns the target object. For example:

const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };
const merged = [Link]({}, obj1, obj2);
[Link](merged); // { a:1, b:3, c:4 }

9
MDN (via GeeksforGeeks) describes it: “The [Link]() method is used to copy the values and properties
from one or more source objects to a target object.” 22 .
- Use cases: Merging objects or cloning (shallow copy). Often used to combine defaults with overrides
( [Link]({}, defaults, options) ). Note that it only does a shallow copy and invokes
setters/getters.

Object Property Shorthand


Q: How does object property shorthand work?
This ES6 shortcut allows writing {x} instead of {x: x} when the key name matches the variable name
10 . Example:

const color = "blue", size = 42;


const item = { color, size };
[Link](item); // { color: "blue", size: 42 }

MDN’s example shows: const o = { a, b, c }; uses shorthand property names 10 . This makes
object creation succinct when variable names match property names. It’s purely syntactic sugar.

Computed Property Names


Q: What are computed property names in objects?
ES6 lets you use an expression in square brackets as an object property key 23 . The expression is evaluated
to get the property name. For example:

const prop = "score";


const obj = {
[prop]: 100,
[`double${prop[0].toUpperCase()}${[Link](1)}`]: 200
};
[Link]([Link]); // 100
[Link]([Link]); // 200

MDN explains: “computed property names… allows you to put an expression in [] that will be computed
and used as the property name” 23 .
- Use cases: Dynamic keys. For instance, you can create object keys based on runtime values (like
generating keys from variables or looping indices) instead of fixed strings.

New Array Methods ( find , findIndex , etc.)


Q: What new array methods did ES6 introduce?
ES6 added [Link]() and findIndex() among others. The find() method returns
the first element that matches a predicate, or undefined if none 24 . The findIndex() method

10
returns the index of the first matching element, or -1 25 . For example:

const array = [5, 12, 8, 130, 44];


[Link]([Link](x => x > 10)); // 12
[Link]([Link](x => x > 10)); // 1
[Link]([1,2,3].includes(2)); // true (checks existence)

MDN describes find() : “returns the first element… that satisfies the provided testing function” 24 , and
findIndex() : “returns the index of the first element… or -1” 25 . It also notes using includes() to
check existence (true/false).
- Use cases: These methods simplify common tasks. Use find / findIndex instead of manual loops to
search by condition. Use includes to check if an array contains a value. They make array processing code
shorter and clearer.

WeakMap and WeakSet


Q: What are WeakMap and WeakSet and why use them?
WeakMap and WeakSet are like Map/Set but hold only object keys (not primitives) and do not prevent
garbage collection of those objects. In a WeakMap , keys must be objects (or symbols), and if there are no
other references to a key object, it can be garbage-collected, along with its value 26 . For example:

let objKey = { id: 1 };


let wm = new WeakMap();
[Link](objKey, "some data");
objKey = null; // object can now be GC'ed, along with its "some data"

MDN explains a WeakMap is a collection where “an object’s presence as a key… does not prevent the object
from being garbage collected” 26 . A WeakSet similarly holds objects weakly (values only, no enumeration).
- Use cases: Storing metadata or caches about objects without affecting their lifecycle. For example,
attaching additional data to DOM nodes or objects without causing memory leaks. Because there’s no
enumeration or size , they’re suited for cases where you just need to know “does this object have some
associated data?”

Reflect API
Q: What is the Reflect API?
The Reflect object is a namespace for low-level methods that mirror object internals (often matching
Proxy handler methods) 27 . These static methods (like [Link] , [Link] ,
[Link] , etc.) perform the default behavior of fundamental operations. They are not
constructor functions and simply expose internal methods. For example, [Link](target,
property) is like target[property] , and [Link](func, thisArg, args) calls a
function.
- Use cases: Primarily used with Proxies. When writing a Proxy trap, you often delegate to the default
behavior via Reflect . As MDN notes, Proxy traps can invoke corresponding Reflect methods to

11
perform the normal operation 27 . For instance:

const handler = {
get(target, prop, receiver) {
[Link](`Accessing ${prop}`);
return [Link](target, prop, receiver); // default behavior
}
};

Using Reflect ensures correct default behavior and makes proxy code cleaner.

Proxy
Q: What is a Proxy and how does it work?
A Proxy wraps a target object or function and lets you intercept and customize fundamental operations
(property access, assignment, enumeration, etc.). You provide a handler object with trap functions. For
example, a get trap intercepts property reads:

const target = { msg: "hello" };


const proxy = new Proxy(target, {
get(t, prop, receiver) {
[Link](`Property ${prop} was accessed`);
return [Link](t, prop, receiver); // default behavior
}
});
[Link]([Link]); // Logs: Property msg was accessed \n hello

MDN explains that proxy handler functions (traps) define custom behavior for internal methods 28 . It also
notes proxies are often used with the Reflect API: in a trap, you can use [Link] ,
[Link] , etc., to apply the normal behavior (the reflective semantics) when needed 28 .
- Use cases: Metaprogramming and validation. For example, you can create objects with reactive behavior
(tracking property access/assignment), enforce security (block certain operations), or auto-complete
properties. Proxies are powerful but advanced; they enable patterns like object wrappers or mocking
objects in tests.

Sources: Feature definitions and examples are based on current MDN documentation and educational
sources 29 2 30 4 5 6 7 8 9 10 11 23 12 13 14 15 16 17 18 19 20 1 22 24 25
26 27 28 .

12
1 29 let - JavaScript | MDN
[Link]

2 const - JavaScript | MDN


[Link]

3 30 Difference between var, let and const keywords in JavaScript | GeeksforGeeks


[Link]

4 Arrow functions in JavaScript | GeeksforGeeks


[Link]

5 Template literals (Template strings) - JavaScript | MDN


[Link]

6 Default parameters - JavaScript | MDN


[Link]

7 Rest parameters - JavaScript | MDN


[Link]

8 Spread syntax (...) - JavaScript | MDN


[Link]

9 Destructuring - JavaScript | MDN


[Link]

10 11 23 Object initializer - JavaScript | MDN


[Link]

12 Classes - JavaScript | MDN


[Link]

13 JavaScript modules - JavaScript | MDN


[Link]

14 Promise - JavaScript | MDN


[Link]

15 Iterators and generators - JavaScript | MDN


[Link]

16 for...of - JavaScript | MDN


[Link]

17 function* - JavaScript | MDN


[Link]

18 Map - JavaScript | MDN


[Link]

19 Set - JavaScript | MDN


[Link]

20 Symbol - JavaScript | MDN


[Link]

13
21 ES6 New String Methods | GeeksforGeeks
[Link]

22 JavaScript Object assign() Method | GeeksforGeeks


[Link]

24 [Link]() - JavaScript | MDN


[Link]

25 [Link]() - JavaScript | MDN


[Link]

26 WeakMap - JavaScript | MDN


[Link]

27 Reflect - JavaScript | MDN


[Link]

28 Proxy - JavaScript | MDN


[Link]

14

You might also like