JavaScript ES6


What is ES6?

ES6, also known as ECMAScript 2015, is the sixth edition of the ECMAScript language specification. It introduced several new features and improvements to JavaScript, making it more powerful and easier to work with.


What are some key features introduced in ES6?

Key features introduced in ES6 include:

  • Arrow Functions: A concise way to write function expressions.
  • let and const: Block-scoped variable declarations.
  • Template Literals: String literals allowing embedded expressions and multi-line strings.
  • Destructuring Assignment: A syntax for unpacking values from arrays or properties from objects into distinct variables.
  • Default Parameters: Allowing named parameters to be initialized with default values if no value or undefined is passed.
  • Rest and Spread Operators: Allowing for easier manipulation of arrays and objects.
  • Classes: A syntactical sugar over JavaScript's existing prototype-based inheritance.
  • Promises: A new way to handle asynchronous operations.
  • Modules: Support for modular programming with import and export syntax.

Can you provide an example of an arrow function?


const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

What is the difference between let, const, and var?

The differences are as follows:

  • var: Function-scoped or globally scoped; can be re-declared and updated.
  • let: Block-scoped; can be updated but not re-declared in the same block.
  • const: Block-scoped; cannot be updated or re-declared and must be initialized at declaration.

// Example of let and const
let x = 1;
const y = 2;

// x = 3; // Allowed
// y = 4; // TypeError: Assignment to constant variable

What are template literals and how do you use them?

Template literals are string literals that allow for multi-line strings and string interpolation using backticks (`).


const name = 'Alice';
const greeting = `Hello, ${name}! 
Welcome to ES6.`;
console.log(greeting);
// Outputs:
// Hello, Alice!
// Welcome to ES6.

What is destructuring assignment?

Destructuring assignment is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.


// Array destructuring
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;
console.log(firstColor); // red

// Object destructuring
const person = { name: 'Alice', age: 30 };
const { name, age } = person;
console.log(name); // Alice

What are default parameters in ES6?

Default parameters allow you to initialize named parameters with default values if no value or undefined is passed.


function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5)); // 5 (uses default value for b)
console.log(multiply(5, 2)); // 10

What are the rest and spread operators?

The rest operator (...) allows you to represent an indefinite number of arguments as an array. The spread operator (...) allows an iterable (like an array) to be expanded in places where zero or more arguments or elements are expected.


// Rest operator
function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 10

// Spread operator
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4]

How do you define a class in ES6?

You can define a class in ES6 using the class keyword. Classes are syntactical sugar over JavaScript's existing prototype-based inheritance.


class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const alice = new Person('Alice', 30);
alice.greet(); // Hello, my name is Alice

What is a promise and how is it used in ES6?

A promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Promises are used to handle asynchronous tasks more effectively and to avoid callback hell.


const myPromise = new Promise((resolve, reject) => {
  // Simulate asynchronous operation
  const success = true; // Change to false to simulate error
  if (success) {
    resolve('Operation successful!');
  } else {
    reject('Operation failed!');
  }
});

myPromise
  .then(result => console.log(result)) // Outputs: Operation successful!
  .catch(error => console.error(error));

What is the module system in ES6?

ES6 introduced a module system that allows you to export and import code between different files. This promotes modular programming and better organization of code.


// module.js
export const PI = 3.14;
export function calculateArea(radius) {
  return PI * radius * radius;
}

// main.js
import { PI, calculateArea } from './module.js';
console.log(PI); // 3.14
console.log(calculateArea(5)); // 78.5
Ads