
JavaScript Cheatsheet
23 of 23 code examples
Variables
Variable declarations
Basicsconst name = "John"; // Constant
let age = 25; // Mutable
var count = 10; // Function scoped
Data Types
Primitive types
Basicsconst str = "Hello"; // String
const num = 42; // Number
const bool = true; // Boolean
const nothing = null; // Null
const notDefined = undefined; // Undefined
const sym = Symbol('id'); // Symbol
Operators
Common operators
Basics// Arithmetic
console.log(10 + 5); // 15
console.log(10 ** 2); // 100
// Comparison
console.log(5 > 3); // true
console.log(5 === '5'); // false
// Logical
console.log(true && false); // false
console.log(true || false); // true
Conditionals
If/else and ternary
Basics// If/else
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
// Ternary
const status = age >= 18 ? "Adult" : "Minor";
// Switch
switch (day) {
case 'Monday':
console.log("Week start");
break;
default:
console.log("Other day");
}
Loops
Different loop types
Basics// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let count = 0;
while (count < 3) {
count++;
}
// For...of
for (const item of array) {
console.log(item);
}
Functions
Function declarations
Functions// Function declaration
function greet(name) {
return `Hello ${name}`;
}
// Arrow function
const add = (a, b) => a + b;
// Default parameters
function createUser(name, age = 18) {
return { name, age };
}
Arrays
Array methods
Data Structuresconst nums = [1, 2, 3];
// Common methods
nums.push(4); // Add to end
nums.pop(); // Remove from end
nums.map(n => n * 2); // [2, 4, 6]
nums.filter(n => n > 1); // [2, 3]
nums.find(n => n > 1); // 2
Objects
Object manipulation
Data Structuresconst person = {
name: "Alice",
age: 30,
greet() {
return `Hello ${this.name}`;
}
};
// Access
person.name; // "Alice"
person['age']; // 30
// Destructuring
const { name, age } = person;
Classes
ES6 classes
OOPclass Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello ${this.name}`;
}
}
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
}
Promises
Async operations
Async// Create promise
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("Done!"), 1000);
});
// Use promise
promise.then(result => console.log(result));
Async/Await
Modern async syntax
Asyncasync function fetchData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
Destructuring
Array and object destructuring
ES6+// Array destructuring
const [first, second] = [1, 2, 3];
// Object destructuring
const { name, age } = { name: "John", age: 30 };
// With defaults
const { theme = "light" } = options;
Spread/Rest
Spread and rest operators
ES6+// Spread
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // {a:1, b:2}
// Rest
const [first, ...rest] = [1, 2, 3]; // rest = [2, 3]
Template Literals
String templates
ES6+const name = "Alice";
const age = 30;
// Basic template
const greeting = `Hello ${name}!`;
// Multi-line
const message = `
Name: ${name}
Age: ${age}
`;
Modules
ES6 modules
Modules// Export
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class Calculator {}
// Import
import Calculator, { PI, add } from './math.js';
Array Methods
Common array methods
Data Structuresconst numbers = [1, 2, 3, 4];
numbers.map(x => x * 2); // [2, 4, 6, 8]
numbers.filter(x => x > 2); // [3, 4]
numbers.reduce((a, b) => a + b, 0); // 10
numbers.find(x => x > 2); // 3
numbers.some(x => x > 3); // true
numbers.every(x => x > 0); // true
Object Methods
Object utilities
Data Structuresconst person = { name: "John", age: 30 };
Object.keys(person); // ['name', 'age']
Object.values(person); // ['John', 30]
Object.entries(person); // [['name','John'], ['age',30]]
// Copy object
const copy = { ...person };
const assigned = Object.assign({}, person);
Error Handling
Try/catch blocks
Error Handlingtry {
// Risky operation
const result = riskyFunction();
} catch (error) {
console.error('Caught error:', error.message);
} finally {
console.log('Always runs');
}
Set/Map
Modern collections
Data Structures// Set - unique values
const unique = new Set([1, 2, 2, 3]); // {1, 2, 3}
// Map - key-value pairs
const map = new Map();
map.set('name', 'Alice');
map.get('name'); // 'Alice'
Optional Chaining
Safe property access
ES6+const user = { profile: { name: "John" } };
// Safe access
const userName = user?.profile?.name; // "John"
const missing = user?.missing?.prop; // undefined
// With nullish coalescing
const name = user?.name ?? 'Anonymous';
Fetch API
HTTP requests
Browser APIsfetch('/api/users')
.then(response => response.json())
.then(users => console.log(users))
.catch(error => console.error(error));
Local Storage
Browser storage
Browser APIs// Store data
localStorage.setItem('user', 'Alice');
// Retrieve data
const user = localStorage.getItem('user');
// Remove data
localStorage.removeItem('user');
Timers
setTimeout & setInterval
Utilities// Run once after delay
setTimeout(() => {
console.log('After 2 seconds');
}, 2000);
// Run repeatedly
const interval = setInterval(() => {
console.log('Every second');
}, 1000);
// Clear interval
clearInterval(interval);