Sobes.tech
Junior

What new features are you familiar with in ES6?

sobes.tech AI

Answer from AI

  • let, const, var: use let and const for block scope, var for function scope. const for constants, let for variables that can be reassigned.
  • Arrow Functions: shorthand syntax for declaring functions. Lexical this.
  • Template Literals: allow embedding expressions and multiline strings.
    const name = "World";
    const greeting = `Hello, ${name}!`; // "Hello, World!"
    
  • Destructuring Assignment: convenient way to extract values from arrays and objects.
    const person = { firstName: "John", lastName: "Doe" };
    const { firstName, lastName } = person; // firstName = "John", lastName = "Doe"
    
  • Spread operator (...) and Rest parameters (...): Spread for expanding and merging arrays/objects. Rest for collecting remaining function arguments into an array.
    const arr1 = [1, 2];
    const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
    
    function sum(...numbers) {
      return numbers.reduce((acc, current) => acc + current, 0);
    }
    sum(1, 2, 3); // 6
    
  • Classes: syntactic sugar over prototypal inheritance.
    class Car {
      constructor(brand) {
        this.brand = brand;
      }
      drive() {
        console.log(`${this.brand} is driving.`);
      }
    }
    
  • Modules: tool for organizing code using import and export.
    // module.js
    export const PI = 3.14;
    
    // main.js
    import { PI } from './module.js';
    
  • Promises: simplify working with asynchronous code.
    new Promise((resolve, reject) => {
      // Asynchronous operation
      if (success) {
        resolve("Success!");
      } else {
        reject("Error!");
      }
    })
    .then(result => console.log(result))
    .catch(error => console.error(error));
    
  • for...of loop: iterate over iterable objects (arrays, strings, Map, Set, etc.).
    const arr = [1, 2, 3];
    for (const value of arr) {
      console.log(value); // 1, 2, 3
    }
    
  • Set and Map: new data structures. Set for unique values, Map for key-value pairs.