Modern JavaScript: Exploring the Latest Features and Enhancements
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:
Block-scoped variables declarations:
let x = 10;
const PI = 3.14;
Concise syntax for writing function expressions:
const sum = (a, b) => a + b;
console.log(sum(2, 3)); // Output: 5
Enhanced way to work with strings:
const name = 'John';
console.log(`Hello, ${name}!`); // Output: Hello, John!
Easily extract values from arrays or properties from objects:
const [a, b] = [1, 2];
const {name, age} = {name: 'John', age: 30};
Set default values for function parameters:
function greet(name = 'Guest') {
return `Hello, ${name}!`;
}
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]
Syntactical sugar over JavaScript's existing prototype-based inheritance:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
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);
}