Top ES6 (ECMAScript 2015) Interview Questions and Answers

What is ES6 (ECMAScript 2015)?

ES6, also known as ECMAScript 2015, is a major update to the JavaScript language. Released in June 2015, it introduced many new features to improve the language's expressiveness, readability, and capabilities for building complex applications. Key additions include modules, classes, arrow functions, promises, and more.

What is ECMAScript?

ECMAScript is a standardized specification for scripting languages. JavaScript is the most popular implementation of ECMAScript.

New Features in ES6

ES6 introduced many significant features:

  • let and const keywords for variable declarations.
  • Default parameters for functions.
  • Arrow functions (concise function syntax).
  • Template literals (for creating multiline strings and interpolating variables).
  • Object literal enhancements.
  • Rest and spread syntax.
  • Destructuring assignment.
  • Modules.
  • Classes.
  • Generators and iterators.
  • Promises.

let and const Keywords

let const
Declares a block-scoped variable; mutable (can be reassigned). Declares a block-scoped constant; immutable (cannot be reassigned).

Arrow Functions in ES6

Arrow functions provide a concise syntax for writing functions. They have lexical scoping (this refers to the surrounding context).

Syntax

const myFunc = (param1, param2) => {
  // Function body
  return param1 + param2; 
};
        

Advantages of Arrow Functions

  • Concise syntax.
  • Lexical this binding.
  • Implicit return for single-expression functions.

Spread Syntax in ES6

The spread syntax (...) expands an iterable (array, string) into individual elements. It's used for array concatenation and creating copies of arrays.

Example

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

Rest Parameters in ES6

Rest parameters (...args) allow a function to accept any number of arguments, collecting them into an array.

Example

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

Template Literals in ES6

Template literals (using backticks ``) provide a concise way to create multiline strings and embed expressions within strings (interpolation).

Example

let name = "Alice";
let message = `Hello, ${name}!`; // message = "Hello, Alice!"
        

Destructuring Assignment in ES6

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

Example: Array Destructuring

let [a, b] = [10, 20]; // a = 10, b = 20
        
Example: Object Destructuring

let { name, age } = { name: "Bob", age: 30 }; // name = "Bob", age = 30
        

Classes in ES6

ES6 introduces classes, providing a more familiar syntax for creating objects and handling inheritance. Classes are syntactical sugar over JavaScript's prototype-based inheritance.

Example Class Definition

class MyClass {
  constructor(param) { this.myProperty = param; }
  myMethod() { return this.myProperty; }
}
        

Generator Functions in ES6

Generator functions (using the function* syntax) can be paused and resumed, making them useful for creating iterators and handling asynchronous operations efficiently. They return a generator object that can be used to control the function's execution.

Example Generator Function

function* myGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

let generator = myGenerator();
console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
        

Default Parameters in ES6

Default parameters allow you to specify default values for function parameters. If a value is not provided for a parameter when calling the function, the default value is used.

Example

function greet(name = "Guest") {
  console.log(`Hello, ${name}!`);
}

greet();       // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
        

IIFEs (Immediately Invoked Function Expressions)

IIFEs are anonymous functions that execute immediately after they're defined. They're useful for creating private scopes and avoiding variable name collisions.

Example

(function() {
  let message = "Hello from IIFE!";
  console.log(message);
})();
        

for...in Loop

The for...in loop iterates over the enumerable properties of an object.

Example

let myObject = { a: 1, b: 2, c: 3 };
for (let key in myObject) {
  console.log(key + ": " + myObject[key]);
}
        

for...of Loop

The for...of loop iterates over the values of iterable objects (arrays, strings, maps, sets).

Example

let arr = [10, 20, 30];
for (let value of arr) {
  console.log(value);
}
        

Sets in ES6

Sets store unique values. They're useful for removing duplicates from a collection.

Example

let mySet = new Set([1, 2, 2, 3]); // mySet = {1, 2, 3}
        

Maps in ES6

Maps store key-value pairs, similar to objects but allowing any data type as keys.

Example

let myMap = new Map([['a', 1], ['b', 2]]);
        

WeakSets in ES6

WeakSets are similar to Sets but hold weak references to objects. They don't prevent garbage collection of the objects they contain.

WeakMaps in ES6

WeakMaps are similar to Maps but hold weak references to objects as keys. They don't prevent garbage collection of the keys.

Promises in ES6

Promises handle asynchronous operations in JavaScript more cleanly than callbacks. They represent the eventual result of an asynchronous operation.

Promise States in ES6

Promises in JavaScript have three states:

  • Pending: The initial state; the result is not yet available.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed.

Once a promise is fulfilled or rejected, its state is immutable (cannot change).

Callbacks and Callback Hell in JavaScript

A callback function is passed as an argument to another function and executed after the other function completes. Callbacks are commonly used for handling asynchronous operations. Callback hell refers to excessively nested callbacks, making code difficult to read and maintain.

ES5 vs. ES6: Key Differences

ES5 ES6
Fifth edition of ECMAScript (2009). Sixth edition of ECMAScript (2015); also known as ECMAScript 2015.
Uses var for variable declarations (function-scoped). Introduces let (block-scoped) and const (block-scoped, immutable) for variable declarations.
Uses function keyword to define functions. Introduces arrow functions (=>).
Limited object manipulation features. Improved object manipulation with destructuring and spread syntax.
No modules. Supports modules (for code organization and reusability).
Limited support for asynchronous programming (callbacks). Introduces Promises for improved handling of asynchronous operations.
No classes (prototype-based inheritance). Introduces classes (syntactical sugar for prototype-based inheritance).

Modules in JavaScript

JavaScript modules are self-contained units of code that can be imported and used in other modules. This promotes better code organization and reusability.

Hoisting in JavaScript

Hoisting is JavaScript's behavior of moving declarations (of variables and functions) to the top of their scope before code execution. This can sometimes lead to unexpected behavior if not understood.

New Array Methods in ES6

  • Array.from()
  • Array.of()
  • copyWithin()
  • find()
  • findIndex()
  • entries()
  • keys()
  • values()
  • fill()

New String Methods in ES6

  • startsWith()
  • endsWith()
  • includes()
  • repeat()

Babel

Babel is a JavaScript compiler (transpiler) that converts modern JavaScript code (like ES6+) into older versions of JavaScript that are supported by most browsers.

Webpack

Webpack is a module bundler for JavaScript. It's often used with Babel and other tools to manage and bundle the code for web applications. It facilitates using modules and managing dependencies efficiently.

Splat Operator in CoffeeScript

The splat operator (...) allows you to pass a variable number of arguments to a function. These arguments are collected into an array.

Example

myFunction = (a, b, ...rest) ->
  console.log(a, b, rest)

myFunction(1, 2, 3, 4, 5)  // Output: 1 2 [3,4,5]
        

Splat with Trailing Argument

A trailing argument can be placed after the splat operator.

Example

myFunction = (a, ...rest, b) ->
  console.log(a, rest, b)

myFunction(1, 2, 3, 4) // Output: 1 [2,3] 4
        

Comprehensions with Splats

You can use list comprehensions to iterate over splatted arguments.

Example

myFunction = (numbers...) ->
  squares = [num * num for num in numbers]
  console.log squares

myFunction(1, 2, 3) // Output: [1, 4, 9]
        

CoffeeScript Math Functions

CoffeeScript provides access to all the JavaScript math functions.