ES6 (ECMAScript 2015) introduced several new features and improvements to JavaScript, making the language more powerful and easier to use. Below are some of the key features of ES6:
The let
and const
keywords provide block-scoping for variables, replacing the older var
.
let name = "John";
const age = 30;
name = "Doe";
age = 35;
Output: TypeError: Assignment to constant variable
Arrow functions provide a concise syntax for writing functions and lexically bind the this
value.
const add = (a, b) => a + b;
console.log(add(2, 3));
Output: 5
Template literals allow embedding expressions inside strings using backticks (`
) and the ${}
syntax.
const name = "Alice";
console.log(`Hello, ${name}!`);
Output: Hello, Alice!
Functions can now have default parameter values.
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
console.log(greet());
Output: Hello, Guest!
Destructuring allows unpacking values from arrays or properties from objects into variables.
const person = { name: "Bob", age: 25 };
const { name, age } = person;
console.log(name, age);
Output: Bob 25
ES6 introduced import
and export
for modular programming.
// file1.js
export const greet = () => console.log("Hello, World!");
// file2.js
import { greet } from './file1.js';
greet();
Output: Hello, World!
Promises make handling asynchronous operations easier by avoiding callback hell.
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data loaded"), 2000);
});
fetchData.then(data => console.log(data));
Output (after 2 seconds): Data loaded
ES6 features bring modern and efficient tools to JavaScript development, making code easier to write and understand.