JavaScript ES6+ Features Quick Reference Guide
Table of Contents
1. Arrow Functions
2. Template Literals
3. Destructuring
4. Spread and Rest Operators
5. Promises and Async/Await
6. Classes
7. Modules
8. Array Methods
9. Object Enhancements
10. Map and Set
1. Arrow Functions
Basic Syntax
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
// Single parameter (parentheses optional)
const square = x => x * x;
// No parameters
const greet = () => "Hello World!";
// Multiple statements
const calculate = (x, y) => {
const result = x * y;
return result + 10;
};
Key Differences
No this binding
Cannot be used as constructors
No arguments object
Implicit return for single expressions
2. Template Literals
Basic Usage
const name = "John";
const age = 30;
// Instead of: "Hello, my name is " + name + " and I'm " + age + " years old"
const message = `Hello, my name is ${name} and I'm ${age} years old`;
// Multi-line strings
const html = `
<div>
<h1>${name}</h1>
<p>Age: ${age}</p>
</div>
`;
Tagged Template Literals
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
return result + string + (values[i] ? `<mark>${values[i]}</mark>` : '
}, '');
}
const user = "Alice";
const score = 95;
const result = highlight`User ${user} scored ${score}%`;
3. Destructuring
Array Destructuring
const colors = ['red', 'green', 'blue', 'yellow'];
// Traditional way
const first = colors[0];
const second = colors[1];
// Destructuring
const [first, second, ...rest] = colors;
const [, , third] = colors; // Skip first two elements
// Default values
const [a, b, c = 'default'] = ['x', 'y'];
Object Destructuring
const person = {
name: 'John',
age: 30,
city: 'New York',
country: 'USA'
};
// Basic destructuring
const {name, age} = person;
// Renaming variables
const {name: fullName, age: years} = person;
// Default values
const {name, profession = 'Developer'} = person;
// Nested destructuring
const user = {
id: 1,
profile: {
email: '[email protected]',
settings: {
theme: 'dark'
}
}
};
const {profile: {settings: {theme}}} = user;
4. Spread and Rest Operators
Spread Operator (...)
// Array spreading
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]
// Object spreading
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const combined = {...obj1, ...obj2}; // {a: 1, b: 2, c: 3, d: 4}
// Function arguments
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
sum(...numbers); // Same as sum(1, 2, 3)
Rest Parameters
// Collect remaining arguments
function multiply(multiplier, ...numbers) {
return numbers.map(num => num * multiplier);
}
multiply(2, 1, 2, 3, 4); // [2, 4, 6, 8]
// Object rest
const {a, ...rest} = {a: 1, b: 2, c: 3};
// a = 1, rest = {b: 2, c: 3}
5. Promises and Async/Await
Promises
// Creating a promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve({data: 'Hello World'});
} else {
reject(new Error('Failed to fetch data'));
}
}, 1000);
});
};
// Using promises
fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));
Async/Await
// Async function
async function getData() {
try {
const result = await fetchData();
console log(result);
return result;
} catch (error) {
console.error('Error:', error.message);
throw error;
}
}
// Multiple async operations
async function fetchMultiple() {
try {
// Sequential
const data1 = await fetchData();
const data2 = await fetchData();
// Parallel
const [result1, result2] = await Promise.all([
fetchData(),
fetchData()
]);
return {result1, result2};
} catch (error) {
console.error(error);
}
}
6. Classes
Basic Class Syntax
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method
greet() {
return `Hello, I'm ${this.name}`;
}
// Getter
get info() {
return `${this.name} (${this.age})`;
}
// Setter
set newAge(age) {
if (age > 0) {
this.age = age;
}
}
// Static method
static species() {
return 'Homo sapiens';
}
}
const john = new Person('John', 30);
console.log(john.greet()); // "Hello, I'm John"
Inheritance
class Developer extends Person {
constructor(name, age, language) {
super(name, age); // Call parent constructor
this.language = language;
}
code() {
return `${this.name} codes in ${this.language}`;
}
// Override parent method
greet() {
return `${super.greet()}, I'm a developer!`;
}
}
const dev = new Developer('Alice', 25, 'JavaScript');
7. Modules
Export
// math.js
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export class Calculator {
multiply(a, b) {
return a * b;
}
}
// Default export
export default function subtract(a, b) {
return a - b;
}
Import
// app.js
import subtract, {PI, add, Calculator} from './math.js';
import * as mathUtils from './math.js';
// Usage
console.log(PI);
console.log(add(2, 3));
const calc = new Calculator();
console.log(subtract(5, 3));
8. Modern Array Methods
Essential Methods
const numbers = [1, 2, 3, 4, 5];
const users = [
{name: 'John', age: 30, active: true},
{name: 'Jane', age: 25, active: false},
{name: 'Bob', age: 35, active: true}
];
// map - Transform elements
const doubled = numbers.map(n => n * 2);
const names = users.map(user => user.name);
// filter - Select elements
const evens = numbers.filter(n => n % 2 === 0);
const activeUsers = users.filter(user => user.active);
// reduce - Aggregate data
const sum = numbers.reduce((acc, n) => acc + n, 0);
const avgAge = users.reduce((sum, user) => sum + user.age, 0) / users.length;
// find - First matching element
const user = users.find(user => user.name === 'John');
// some/every - Boolean tests
const hasActive = users.some(user => user.active);
const allAdults = users.every(user => user.age >= 18);
// forEach - Side effects
users.forEach(user => {
console.log(`${user.name}: ${user.age}`);
});
9. Object Enhancements
Property Shorthand
const name = 'John';
const age = 30;
// Old way
const person1 = {
name: name,
age: age
};
// New way
const person2 = {name, age};
Method Shorthand
const calculator = {
// Old way
add: function(a, b) {
return a + b;
},
// New way
multiply(a, b) {
return a * b;
}
};
Computed Property Names
const prop = 'dynamicProperty';
const obj = {
[prop]: 'value',
[`${prop}Count`]: 42
};
10. Map and Set
Map
// Create a Map
const userRoles = new Map();
// Set values
userRoles.set('john', 'admin');
userRoles.set('jane', 'user');
userRoles.set('bob', 'moderator');
// Get values
console.log(userRoles.get('john')); // 'admin'
// Check existence
console.log(userRoles.has('john')); // true
// Iterate
userRoles.forEach((role, user) => {
console.log(`${user}: ${role}`);
});
// Size
console.log(userRoles.size); // 3
Set
// Create a Set
const uniqueNumbers = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(uniqueNumbers); // Set {1, 2, 3, 4, 5}
// Add values
uniqueNumbers.add(6);
// Check existence
console.log(uniqueNumbers.has(3)); // true
// Delete
uniqueNumbers.delete(2);
// Convert to array
const arrayFromSet = [...uniqueNumbers];
Conclusion
These ES6+ features make JavaScript more powerful, readable, and maintainable. Practice
using them in your projects to become proficient with modern JavaScript development.
Quick Reference Cheat Sheet
Arrow Functions: const fn = (a, b) => a + b
Template Literals: `Hello ${name}`
Destructuring: const {a, b} = obj
Spread: [...array], {...object}
Promises: await fetch(url)
Classes: class MyClass extends Parent {}
Modules: import {fn} from './module'