In this post, we’ll break down the most important features of ES6 and how they can improve your code.
1. let and const
Before ES6, we only had var, which behaved unpredictably due to function scoping and hoisting quirks. ES6 introduced:
let
Block-scoped & re-assignable
let counter = 0;
for (let i = 0; i < 5; i++) {
counter += i;
}
const
Block-scoped & not re-assignable
const PI = 3.14;
2. Arrow Functions
Arrow functions make function expressions shorter and automatically bind this.
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
3. Template Literals
Multi-line strings and embedded variables become easy:
const name = "Sarah";
console.log(`Hello, ${name}!`);
4. Default Parameters
Give function parameters default values:
function greet(name = "Guest") {
console.log(`Hello, ${name}`);
}
5. Destructuring
Object Destructuring
const user = { name: "Tom", age: 28 };
const { name, age } = user;
Array Destructuring
const [a, b] = [10, 20];
6. Spread & Rest Operators
Spread:
Expand arrays or objects:
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4];
Rest:
Collect arguments:
function sum(...nums) {
return nums.reduce((a, b) => a + b);
}
7. Classes
Finally, JavaScript got a more familiar OOP syntax:
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I am ${this.name}`;
}
}
8. Modules
ES6 introduced the long-awaited module system:
// add.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from "./add.js";
9. Promises
Promises provide a cleaner alternative to callbacks:
fetch('/data.json')
.then(response => response.json())
.then(data => console.log(data));
10. Enhanced Object Literals
ES6 makes object creation more concise:
const name = "Mike";
const person = {
name,
greet() {
return `Hi, I'm ${this.name}`;
}
};