← Back to Home

JavaScript ES6+ Reference

JavaScript ES6+ Reference

Modern JavaScript reference covering ES6+ features, syntax, and methods. Essential for contemporary web development with the latest language features.

Modern JavaScript

This reference focuses on ES6+ features that are widely supported in modern browsers. Examples use contemporary syntax and best practices for modern web development.

Coverage: ES6/ES2015 through ES2023 | Environment: Modern browsers & Node.js

Variables & Scope

Variable Declarations

// var (function-scoped, hoisted)
var name = 'John';
var age; // undefined
// let (block-scoped, not hoisted)
let count = 0;
let message; // undefined
// const (block-scoped, immutable binding)
const PI = 3.14159;
const user = { name: 'Alice', age: 30 }; // Object is mutable
user.age = 31; // ✅ Allowed
// user = ; // ❌ Error: Assignment to constant variable
// Block scope demonstration
if (true) {
let blockScoped = 'inside block';
var functionScoped = 'available outside';
}
// console.log(blockScoped); // ❌ ReferenceError
console.log(functionScoped); // ✅ 'available outside'

Functions

Arrow Functions

Arrow Function Syntax

// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function (basic)
const add = (a, b) => {
return a + b;
};
// Arrow function (concise)
const add = (a, b) => a + b;
// Single parameter (parentheses optional)
const square = x => x * x;
const square = (x) => x * x; // Same as above
// No parameters
const getRandomNumber = () => Math.random();
// Returning object literal
const createUser = (name, age) => ({ name, age });
// Higher-order functions
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

🔑 Key Differences:

  • • Arrow functions don't have their own `this` binding
  • • Cannot be used as constructors (no `new`)
  • • No `arguments` object (use rest parameters instead)
  • • Implicit return for single expressions

Destructuring

Array Destructuring

// Basic array destructuring
const colors = ['red', 'green', 'blue'];
const [first, second, third] = colors;
console.log(first); // 'red'
// Skipping elements
const [, , third] = colors; // Skip first two
// Default values
const [a = 1, b = 2, c = 3] = [10, 20];
console.log(a, b, c); // 10, 20, 3
// Rest elements
const [head, ...tail] = [1, 2, 3, 4, 5];
console.log(head); // 1
console.log(tail); // [2, 3, 4, 5]
// Swapping variables
let x = 1, y = 2;
[x, y] = [y, x]; // x = 2, y = 1
// Function return values
const getCoordinates = () => [10, 20];
const [x, y] = getCoordinates();

Object Destructuring

// Basic object destructuring
const user = { name: 'Alice', age: 30, city: 'New York' };
const { name, age, city } = user;
console.log(name); // 'Alice'
// Renaming variables
const { name: userName, age: userAge } = user;
console.log(userName); // 'Alice'
// Default values
const { name, email = 'no-email@example.com' } = user;
console.log(email); // 'no-email@example.com'
// Nested destructuring
const person = {
name: 'Bob',
address: { street: '123 Main St', city: 'Boston' }
};
const { name, address: { street, city } } = person;
// Function parameters
function greet({ name, age = 'unknown' }) {
return `Hello ${name}, you are ${age} years old`;
}
greet({ name: 'Charlie', age: 25 });

Spread & 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]
const withExtra = [0, ...arr1, 3.5, ...arr2]; // [0, 1, 2, 3, 3.5, 4, 5, 6]
// Array copying
const original = [1, 2, 3];
const copy = [...original]; // Shallow copy
// Object spreading
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 }; // { a: 1, b: 2, c: 3, d: 4 }
// Object updating
const user = { name: 'Alice', age: 30 };
const updatedUser = { ...user, age: 31 }; // { name: 'Alice', age: 31 }
// Function arguments
const numbers = [1, 2, 3, 4, 5];
console.log(Math.max(...numbers)); // 5
console.log(Math.min(...numbers)); // 1

Rest Parameters (...)

// Rest in function parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Mixed parameters
function greet(greeting, ...names) {
return `${greeting} ${names.join(', ')}!`;
}
console.log(greet('Hello', 'Alice', 'Bob', 'Charlie'));
// "Hello Alice, Bob, Charlie!"
// Rest in destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(second); // 2
console.log(rest); // [3, 4, 5]
// Object rest
const { name, age, ...otherProps } = {
name: 'Alice',
age: 30,
city: 'New York',
job: 'Engineer'
};
console.log(otherProps); // { city: 'New York', job: 'Engineer' }

Template Literals

String Interpolation & Formatting

// Basic interpolation
const name = 'Alice';
const age = 30;
const message = `Hello, my name is ${name} and I'm ${age} years old.`;
// Multi-line strings
const html = `
<div class="user-card">
<h2>${name}</h2>
<p>Age: ${age}</p>
</div>
`;
// Expression evaluation
const price = 29.99;
const quantity = 3;
const total = `Total: $${(price * quantity).toFixed(2)}`;
// Conditional expressions
const status = `User is ${age >= 18 ? 'adult' : 'minor'}`;
// Function calls
const formatDate = (date) => date.toLocaleDateString();
const now = new Date();
const dateString = `Today is ${formatDate(now)}`;
// Tagged templates (advanced)
function highlight(strings, ...values) {
return strings.reduce((result, string, i) => {
const value = values[i] ? `<mark>${values[i]}</mark>` : '';
return result + string + value;
}, '');
}
const highlighted = highlight`Hello ${name}, you are ${age} years old.`;

Array Methods

Essential Array Methods

const numbers = [1, 2, 3, 4, 5];
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 35 }
];
// map - transform each element
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8, 10]
const names = users.map(user => user.name); // ['Alice', 'Bob', 'Charlie']
// filter - select elements that match condition
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
const adults = users.filter(user => user.age >= 30);
// find - first element that matches
const firstEven = numbers.find(n => n % 2 === 0); // 2
const alice = users.find(user => user.name === 'Alice');
// reduce - accumulate values
const sum = numbers.reduce((acc, n) => acc + n, 0); // 15
const totalAge = users.reduce((acc, user) => acc + user.age, 0);
// some/every - boolean checks
const hasEven = numbers.some(n => n % 2 === 0); // true
const allPositive = numbers.every(n => n > 0); // true
// forEach - side effects (avoid for pure functions)
numbers.forEach(n => console.log(n));

Advanced Array Operations

// flatMap - map then flatten
const sentences = ['Hello world', 'How are you'];
const words = sentences.flatMap(s => s.split(' '));
// ['Hello', 'world', 'How', 'are', 'you']
// includes - check if element exists
const fruits = ['apple', 'banana', 'orange'];
const hasApple = fruits.includes('apple'); // true
// indexOf/findIndex - get position
const position = fruits.indexOf('banana'); // 1
const userIndex = users.findIndex(user => user.name === 'Bob'); // 1
// sort - order elements
const sorted = [...numbers].sort((a, b) => a - b); // [1, 2, 3, 4, 5]
const sortedUsers = [...users].sort((a, b) => a.age - b.age);
// slice - extract portion
const firstThree = numbers.slice(0, 3); // [1, 2, 3]
const lastTwo = numbers.slice(-2); // [4, 5]
// concat - combine arrays
const moreNumbers = [6, 7, 8];
const combined = numbers.concat(moreNumbers); // [1, 2, 3, 4, 5, 6, 7, 8]
const combined2 = [...numbers, ...moreNumbers]; // Same result with spread

Objects & Classes

Object Methods

const user = { name: 'Alice', age: 30, city: 'New York' };
// Object.keys - get property names
const keys = Object.keys(user); // ['name', 'age', 'city']
// Object.values - get property values
const values = Object.values(user); // ['Alice', 30, 'New York']
// Object.entries - get key-value pairs
const entries = Object.entries(user);
// [['name', 'Alice'], ['age', 30], ['city', 'New York']]
// Object.assign - shallow copy/merge
const copy = Object.assign({}, user);
const merged = Object.assign({}, user, { email: 'alice@example.com' });
// Object.fromEntries - create object from entries
const fromEntries = Object.fromEntries([
['name', 'Bob'],
['age', 25]
]); // { name: 'Bob', age: 25 }
// hasOwnProperty - check property existence
const hasName = user.hasOwnProperty('name'); // true
const hasEmail = 'email' in user; // false

ES6 Classes

// Basic class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
static species() {
return 'Homo sapiens';
}
}
// Inheritance
class Employee extends Person {
constructor(name, age, jobTitle) {
super(name, age); // Call parent constructor
this.jobTitle = jobTitle;
}
greet() {
return `${super.greet()} I work as a ${this.jobTitle}.`;
}
work() {
return `${this.name} is working as a ${this.jobTitle}`;
}
}
// Usage
const employee = new Employee('Alice', 30, 'Engineer');
console.log(employee.greet());
console.log(Employee.species()); // Static method

Async Programming

Promises

// Creating promises
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const fetchUser = (id) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) {
resolve({ id, name: 'User ' + id });
} else {
reject(new Error('Invalid user ID'));
}
}, 1000);
});
};
// Using promises
fetchUser(1)
.then(user => console.log(user))
.catch(error => console.error(error))
.finally(() => console.log('Done'));
// Promise.all - wait for all
Promise.all([fetchUser(1), fetchUser(2), fetchUser(3)])
.then(users => console.log('All users:', users));
// Promise.race - first to complete
Promise.race([fetchUser(1), delay(500)])
.then(result => console.log('First result:', result));

Async/Await

// Basic async function
async function getUser(id) {
try {
const user = await fetchUser(id);
return user;
} catch (error) {
console.error('Error fetching user:', error);
return null;
}
}
// Sequential operations
async function processUsers() {
const user1 = await fetchUser(1);
const user2 = await fetchUser(2);
const user3 = await fetchUser(3);
return [user1, user2, user3];
}
// Parallel operations
async function processUsersParallel() {
const [user1, user2, user3] = await Promise.all([
fetchUser(1),
fetchUser(2),
fetchUser(3)
]);
return [user1, user2, user3];
}
// Error handling
async function safeOperation() {
try {
const result = await riskyOperation();
return result;
} catch (error) {
console.error('Operation failed:', error.message);
throw error; // Re-throw if needed
}
}

Modules

ES6 Module System

// math.js - Named exports
export const PI = 3.14159;
export function add(a, b) {
return a + b;
}
export const multiply = (a, b) => a * b;
// utils.js - Default export
const formatDate = (date) => {
return date.toLocaleDateString();
};
export default formatDate;
// Mixed exports
export const version = '1.0.0';
export default formatDate;
// Importing named exports
import { PI, add, multiply } from './math.js';
import { add as sum } from './math.js'; // Rename import
// Importing default export
import formatDate from './utils.js';
// Import all as namespace
import * as math from './math.js';
console.log(math.PI, math.add(2, 3));
// Dynamic imports
async function loadMath() {
const math = await import('./math.js');
return math.add(2, 3);
}

DOM Manipulation

Modern DOM APIs

// Query selectors
const element = document.querySelector('.my-class');
const elements = document.querySelectorAll('div');
const byId = document.getElementById('my-id');
// Creating elements
const div = document.createElement('div');
div.textContent = 'Hello World';
div.classList.add('greeting');
div.setAttribute('data-id', '123');
// Modifying content
element.textContent = 'New text content';
element.innerHTML = '<strong>Bold text</strong>';
element.style.color = 'red';
element.style.backgroundColor = 'yellow';
// Class manipulation
element.classList.add('active');
element.classList.remove('inactive');
element.classList.toggle('visible');
element.classList.contains('active'); // true/false
// Event handling
element.addEventListener('click', (event) => {
console.log('Element clicked!', event.target);
});
// Form handling
const form = document.querySelector('form');
const formData = new FormData(form);
const data = Object.fromEntries(formData.entries());

Error Handling

Try-Catch and Error Types

// Basic error handling
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('Error occurred:', error.message);
} finally {
console.log('Cleanup operations');
}
// Throwing custom errors
function validateAge(age) {
if (typeof age !== 'number') {
throw new TypeError('Age must be a number');
}
if (age < 0) {
throw new RangeError('Age cannot be negative');
}
return age;
}
// Custom error class
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
// Error handling with async/await
async function handleAsyncError() {
try {
const data = await fetch('/api/data');
const json = await data.json();
return json;
} catch (error) {
if (error instanceof TypeError) {
console.error('Network error:', error.message);
} else {
console.error('Unexpected error:', error);
}
throw error; // Re-throw if needed
}
}

🚀 Modern JavaScript Best Practices

  • • Use `const` by default, `let` when reassignment is needed, avoid `var`
  • • Prefer arrow functions for callbacks and short functions
  • • Use destructuring for cleaner code and better readability
  • • Leverage array methods like `map`, `filter`, `reduce` over traditional loops
  • • Use template literals for string interpolation and multi-line strings
  • • Prefer `async/await` over promise chains for better readability
  • • Use modules to organize code and avoid global scope pollution
  • • Handle errors appropriately with try-catch blocks

⚡ Modern JavaScript Mastery

ES6+ features have transformed JavaScript development. Practice these patterns to write cleaner, more maintainable code. Stay updated with the latest features and browser support.