ECMAScript 6 (ES6) introduced several new features to JavaScript that simplify coding and enhance functionality. Here, we’ll cover key ES6 features with examples and outputs!
1. Let and Const
Let allows you to declare variables with block scope, while const ensures the variable value cannot be reassigned.
let message = "Hello, ES6!";
console.log(message);
const pi = 3.14159;
console.log(pi);
Output:
2. Arrow Functions
Arrow functions provide a concise syntax for writing functions and maintain the this
context.
const greet = (name) => `Hello, ${name}!`;
console.log(greet("John"));
Output:
3. Template Literals
Template literals allow multi-line strings and string interpolation using backticks (`
).
const name = "Alice";
const greeting = `Welcome to ES6, ${name}!
Have a great day!`;
console.log(greeting);
Output:
4. Default Parameters
Functions can now have default values for parameters.
const multiply = (a, b = 1) => a * b;
console.log(multiply(5)); // 5
console.log(multiply(5, 2)); // 10
Output:
5. Destructuring
Destructuring allows unpacking values from arrays or properties from objects into variables.
// Array Destructuring
const [a, b] = [10, 20];
console.log(a, b);
// Object Destructuring
const user = { name: "Bob", age: 25 };
const { name, age } = user;
console.log(name, age);
Output:
6. Spread and Rest Operator
The spread operator (...
) expands an array or object, while the rest operator collects arguments into an array.
// Spread Operator
const arr = [1, 2, 3];
console.log(...arr);
// Rest Operator
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
console.log(sum(1, 2, 3, 4));
Output:
7. Promises
Promises simplify asynchronous code and replace callbacks.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched!"), 2000);
});
fetchData.then(data => console.log(data));
Output: