Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

ES6 Features (let, const, arrow functions, etc.)

ES6 Features (let, const, arrow functions, etc.)

ES6 (ECMAScript 6), also known as ECMAScript 2015, introduced several important features to JavaScript that significantly improved the language's capabilities. Here are some of the key ES6 features:

1. let and const:

  • let and const are block-scoped variable declarations, providing an alternative to var.
let x = 10; // Variable with block scope
const PI = 3.14; // Constant with block scope (cannot be reassigned)
 

2. Arrow Functions:

  • Arrow functions provide a more concise syntax for defining functions.
// Traditional function
function add(x, y) {
  return x + y;
}

// Arrow function
const add = (x, y) => x + y;
 

3. Template Literals:

  • Template literals allow for more readable string interpolation and multi-line strings.
let name = 'John';
let greeting = `Hello, ${name}!
How are you today?`;
 

4. Destructuring Assignment:

  • Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a concise way.
// Array destructuring
const [a, b, c] = [1, 2, 3];

// Object destructuring
const { firstName, lastName } = { firstName: 'John', lastName: 'Doe' };
 

5. Spread and Rest Operators:

  • The spread operator (...) allows for the expansion of elements in arrays or objects, while the rest operator collects multiple elements into a single array.
// Spread operator
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // Results in [1, 2, 3, 4, 5]

// Rest operator
function sum(...args) {
  return args.reduce((total, current) => total + current, 0);
}
 

6. Object Literal Enhancements:

  • ES6 allows you to define object properties with dynamic keys and values more easily.
let key = 'name';
let value = 'John';

let person = {
  [key]: value, // Dynamic property name
  sayHello() { // Shorthand for function
    console.log(`Hello, ${this.name}!`);
  }
};
 

7. Classes:

  • ES6 introduced a more concise syntax for defining classes and working with inheritance.
class Person {
  constructor(name) {
    this.name = name;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}
 

8. Modules:

  • ES6 introduced a standardized way to organize code into modules, making it easier to manage dependencies.
// Exporting module
export function add(x, y) {
  return x + y;
}

// Importing module
import { add } from './math';