ES6+ Features

Modern JavaScript: Exploring the Latest Features and Enhancements

ES6+ Features in JavaScript

ES6 (ECMAScript 2015) and subsequent versions have introduced many new features to JavaScript, making the language more powerful and expressive. Here are some key features:

Let and Const

Block-scoped variables declarations:

let x = 10;
const PI = 3.14;

Arrow Functions

Concise syntax for writing function expressions:

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

Template Literals

Enhanced way to work with strings:

const name = 'John';
console.log(`Hello, ${name}!`); // Output: Hello, John!

Destructuring

Easily extract values from arrays or properties from objects:

const [a, b] = [1, 2];
const {name, age} = {name: 'John', age: 30};

Default Parameters

Set default values for function parameters:

function greet(name = 'Guest') {
return `Hello, ${name}!`;
}

Rest and Spread Operators

Collect multiple elements into an array or spread an array into individual elements:

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

const arr = [1, 2, 3];
console.log([...arr, 4, 5]); // Output: [1, 2, 3, 4, 5]

Classes

Syntactical sugar over JavaScript's existing prototype-based inheritance:

class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a sound.`);
}
}

Promises and Async/Await

Better ways to handle asynchronous operations:

const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data fetched!'), 2000);
});
};

async function getData() {
const result = await fetchData();
console.log(result);
}