ES6 Features Cheat Sheet (with Explanation & Examples)
1. let and const
Introduced block-scoping. `let` allows reassignment but is block-scoped. `const` is block-scoped and immutable (cannot
be reassigned).
let name = "Manohar";
const age = 30;
if (true) {
let name = "Carter";
console.log("Inside block:", name); // Carter
}
console.log("Outside block:", name); // Manohar
2. Arrow Functions
Provides shorter syntax for writing functions and automatically binds `this` from the surrounding context.
const greet = (user) => `Hello, ${user}!`;
console.log(greet("Manohar"));
3. Template Literals
Use backticks (`) for strings. Supports multiline strings and embedding expressions using `${}`.
const lang = "JavaScript";
const message = `Welcome to ES6 with ${lang}!`;
console.log(message);
4. Default Parameters
Functions can now assign default values to parameters if no value or `undefined` is passed.
function sayHello(name = "Guest") {
console.log(`Hello, ${name}`);
}
sayHello(); // Hello, Guest
sayHello("Ravi"); // Hello, Ravi
5. Destructuring
Allows unpacking values from arrays or properties from objects into distinct variables.
const [x, y] = [10, 20];
console.log(x, y); // 10 20
const user = { id: 1, name: "Manohar" };
const { name, id } = user;
console.log(name, id);
6. Spread and Rest Operators
Spread (`...`) expands arrays or objects. Rest (`...`) collects multiple elements into an array.
const nums = [1, 2, 3];
const moreNums = [...nums, 4, 5];
ES6 Features Cheat Sheet (with Explanation & Examples)
console.log(moreNums);
function multiply(multiplier, ...values) {
return values.map(n => n * multiplier);
}
console.log(multiply(2, 1, 2, 3));
7. Enhanced Object Literals
Simplified syntax for object properties and methods. Great for cleaner code.
const fruit = "apple";
const quantity = 10;
const cartItem = {
fruit,
quantity,
print() {
console.log(`${this.quantity} ${this.fruit}s in cart.`);
}
};
cartItem.print();
8. Promises
Promises provide a clean way to handle asynchronous operations. Use `.then()` for success and `.catch()` for errors.
const fetchData = () => {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
};
fetchData().then(console.log);
9. Classes
Syntactic sugar over prototypes. Enables easier creation of objects and inheritance.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
const dog = new Animal("Dog");
dog.speak();
10. Modules (import/export)
ES6 Features Cheat Sheet (with Explanation & Examples)
Used to split JavaScript code into reusable files. Use `export` in one file and `import` in another.
// math.js
export const add = (a, b) => a + b;
// main.js
import { add } from './math.js';
console.log(add(5, 3));