JavaScript Cheat Sheet
A comprehensive guide to essential JavaScript syntax and features for modern web development.
Variables and Data Types
// Variable declarations
var oldWay = "function scoped";
let blockScoped = "block scoped";
const constant = "cannot reassign";
// Data types
let string = "Hello World";
let number = 42;
let boolean = true;
let array = [1, 2, 3, 4];
let object = { name: "John", age: 30 };
let nullValue = null;
let undefinedValue = undefined;
let symbol = Symbol("unique");
Variables: string: "Hello World", number: 42, boolean: true, array: [1,2,3,4]
Functions
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const greetExpression = function(name) {
return `Hello, ${name}!`;
};
// Arrow functions
const greetArrow = (name) => `Hello, ${name}!`;
const add = (a, b) => a + b;
const multiply = (a, b) => {
return a * b;
};
// Default parameters
function greetWithDefault(name = "World") {
return `Hello, ${name}!`;
}
// Rest parameters
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
Function Examples:
greet("Alice") β "Hello, Alice!"
add(5, 3) β 8
greetWithDefault() β "Hello, World!"
sum(1, 2, 3, 4) β 10
Objects and Arrays
// Object creation and manipulation
const person = {
name: "John",
age: 30,
city: "New York"
};
// Accessing properties
console.log(person.name); // "John"
console.log(person["age"]); // 30
// Adding/modifying properties
person.email = "john@example.com";
person.age = 31;
// Object destructuring
const { name, age } = person;
// Array methods
const numbers = [1, 2, 3, 4, 5];
// Map, filter, reduce
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);
// Array destructuring
const [first, second, ...rest] = numbers;
Object and Array Examples:
person.name β "John"
doubled β [2, 4, 6, 8, 10]
evens β [2, 4]
sum β 15
first β 1, second β 2, rest β [3, 4, 5]
Control Flow
// If statements
if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
}
// Ternary operator
const result = condition ? "true value" : "false value";
// Switch statement
switch (value) {
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
default:
console.log("Other");
}
// Loops
for (let i = 0; i < 5; i++) {
console.log(i);
}
for (const item of array) {
console.log(item);
}
for (const key in object) {
console.log(key, object[key]);
}
while (condition) {
// code
}
Control Flow Examples:
Ternary: true ? "yes" : "no" β "yes"
For loop: 0, 1, 2, 3, 4
For-of: iterates over values
For-in: iterates over keys
Classes and Objects
// ES6 Classes
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 Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
return `${this.name} is studying`;
}
}
// Object creation
const john = new Person("John", 30);
const alice = new Student("Alice", 20, "A");
Class Examples:
john.greet() β "Hello, I'm John"
Person.species() β "Homo sapiens"
alice.study() β "Alice is studying"
Promises and Async/Await
// Promises
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully");
}, 1000);
});
};
// Promise chaining
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
// Async/Await
async function getData() {
try {
const data = await fetchData();
console.log(data);
return data;
} catch (error) {
console.error(error);
}
}
// Multiple async operations
async function getMultipleData() {
const [data1, data2] = await Promise.all([
fetchData(),
fetchData()
]);
return { data1, data2 };
}
Async Examples:
Promise resolves after 1 second
async/await provides cleaner syntax
Promise.all() runs operations concurrently
DOM Manipulation
// Selecting elements
const element = document.getElementById('myId');
const elements = document.querySelectorAll('.myClass');
const firstElement = document.querySelector('.myClass');
// Creating elements
const newDiv = document.createElement('div');
newDiv.textContent = 'Hello World';
newDiv.className = 'my-class';
// Modifying elements
element.textContent = 'New text';
element.innerHTML = '<strong>Bold text</strong>';
element.style.color = 'red';
element.setAttribute('data-value', '123');
// Event listeners
element.addEventListener('click', function(event) {
console.log('Element clicked!');
});
// Arrow function event listener
element.addEventListener('click', (event) => {
event.preventDefault();
console.log('Clicked with arrow function');
});
DOM Examples:
This text can be modified
Error Handling
// Try-catch blocks
try {
const result = riskyOperation();
console.log(result);
} catch (error) {
console.error('An error occurred:', error.message);
} finally {
console.log('This always runs');
}
// Custom errors
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
function validateAge(age) {
if (age < 0) {
throw new CustomError('Age cannot be negative');
}
return true;
}
// Error handling with async/await
async function handleAsyncError() {
try {
const data = await fetchData();
return data;
} catch (error) {
console.error('Async error:', error);
throw error;
}
}
Error Handling:
Try-catch blocks handle synchronous errors
Custom errors provide specific error types
Async error handling with try-catch in async functions
ES6+ Features
// Template literals
const name = "World";
const greeting = `Hello, ${name}!`;
const multiline = `
This is a
multiline string
`;
// Destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
const {x, y, z = 'default'} = {x: 1, y: 2};
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
const obj1 = {a: 1, b: 2};
const obj2 = {c: 3, d: 4};
const combinedObj = {...obj1, ...obj2};
// Optional chaining
const user = {
profile: {
name: 'John'
}
};
const userName = user?.profile?.name; // "John"
const userAge = user?.profile?.age; // undefined
// Nullish coalescing
const value = null ?? 'default'; // "default"
const value2 = '' ?? 'default'; // "" (empty string is not null/undefined)
ES6+ Examples:
Template literal: `Hello, ${name}!` β "Hello, World!"
Spread: [...[1,2], ...[3,4]] β [1, 2, 3, 4]
Optional chaining prevents errors on undefined properties
Nullish coalescing: null ?? 'default' β 'default'
Common Utilities
// Type checking
typeof "hello"; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (quirk!)
Array.isArray([1, 2, 3]); // true
// String methods
"hello world".toUpperCase(); // "HELLO WORLD"
" hello ".trim(); // "hello"
"hello,world".split(","); // ["hello", "world"]
"hello".includes("ell"); // true
// Number methods
parseInt("123"); // 123
parseFloat("123.45"); // 123.45
Math.round(123.456); // 123
Math.max(1, 2, 3); // 3
Math.random(); // 0 to 1
// Date handling
const now = new Date();
const timestamp = Date.now();
const dateString = now.toISOString();
Utility Examples:
typeof "hello" β "string"
"HELLO".toLowerCase() β "hello"
Math.round(4.7) β 5
Current timestamp:
This JavaScript cheat sheet covers the most essential features and syntax for modern web development. Practice with these concepts to master JavaScript!