JavaScript

Modern Cheatsheet • by @CodersStudy

📦

Variables & Data Types

Variable Declarations
var name = "Old way"; // Function-scoped
let age = 25; // Block-scoped
const PI = 3.14159; // Immutable
Primitive Types
let str = "Hello"; // String
let num = 42; // Number
let bool = true; // Boolean
let nothing = null; // Null
let undef; // Undefined
ES6+
let sym = Symbol('id');
let big = 123n; // BigInt

Operators

Arithmetic
+Addition
-Subtraction
*Multiplication
/Division
%Modulus
**Exponentiation
Comparison
=== // Strict equal
!== // Strict not equal
< > <= >= // Comparison
Logical
&& // AND
|| // OR
! // NOT
?? // Nullish coalescing
🔄

Control Flow

Conditionals
if (condition) {
// code
} else if (condition2) {
// code
} else {
// code
}
Loops
for (let i = 0; i < 10; i++) { }
for (let key in obj) { }
for (let val of arr) { }
while (condition) { }
Ternary
let result = condition ? value1 : value2;
⚙️

Functions

Function Types
// Function declaration
function myFunc(param) {
return param;
}
// Arrow function
const myFunc = (param) => param;
Advanced Features
// Default parameters
function greet(name = "World") { }
// Rest parameters
function sum(...numbers) { }
📊

Arrays

Common Methods
arr.push(item) // Add to end
arr.pop() // Remove from end
arr.shift() // Remove from start
arr.unshift(item) // Add to start
Iteration Methods
arr.map(fn) // Transform
arr.filter(fn) // Filter
arr.reduce(fn, init) // Reduce
arr.forEach(fn) // Execute
arr.find(fn) // Find first
Modern
[...new Set(arr)] // Remove duplicates
🎯

Objects

Object Methods
Object.keys(obj) // Get keys
Object.values(obj) // Get values
Object.entries(obj) // Get pairs
Object.assign(target, src) // Copy
Destructuring
const {name, age} = person;
const {name: personName} = person;
const [first, second] = array;
📝

Strings

String Methods
str.length // Length
str.charAt(index) // Character at
str.indexOf(sub) // Find substring
str.slice(start, end) // Extract
str.replace(old, new) // Replace
Template Literals
`Hello ${name}, age ${age}`
🌐

DOM Manipulation

Selecting Elements
document.getElementById('id')
document.querySelector('.class')
document.querySelectorAll('.class')
Manipulation
element.innerHTML = 'content'
element.textContent = 'text'
element.classList.add('class')
element.style.property = 'value'

Events

Event Handling
element.addEventListener('click', fn)
element.removeEventListener('click', fn)
Common Events
'click', 'mouseover', 'mouseout'
'keydown', 'keyup', 'keypress'
'load', 'resize', 'scroll'
'submit', 'change', 'input'

Async Programming

Promises
const promise = new Promise((resolve, reject) => {
if (success) resolve(result);
else reject(error);
});
Async/Await
async function fetchData() {
try {
const data = await fetch(url);
return data;
} catch (error) {
console.error(error);
}
}
🚀

ES6+ Features

Classes
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello ${this.name}`;
}
}
Modules
export const variable = 'value';
export default class MyClass { }
import { variable } from './module.js';
Modern Operators
obj?.prop?.nested // Optional chaining
value ?? 'default' // Nullish coalescing
💡

Quick Tips

Common Patterns
// Check if variable exists
if (typeof variable !== 'undefined') { }
// Convert to number
Number(str), parseInt(str), +str
// Clone array/object
[...arr], {...obj}
Performance Tips
• Use const and let instead of var
• Use strict equality ===
• Cache DOM queries
• Use event delegation
• Prefer for loops for performance-critical code
🛡️

Error Handling

Try-Catch
try {
// Risky code
let result = riskyOperation();
} catch (error) {
console.error('Error:', error.message);
} finally {
// Always executed
cleanup();
}
Custom Errors
throw new Error('Something went wrong');
throw new TypeError('Expected number');
🗃️

Data Structures

Set
const set = new Set([1, 2, 3]);
set.add(4); // Add value
set.has(1); // Check exists
set.delete(2); // Remove value
set.clear(); // Remove all
Map
const map = new Map();
map.set('key', 'value'); // Set key-value
map.get('key'); // Get value
map.has('key'); // Check key exists
map.delete('key'); // Remove key
WeakMap & WeakSet
Similar to Map/Set but with weak references - objects can be garbage collected
🔍

Regular Expressions

Creating RegExp
const regex1 = /pattern/flags;
const regex2 = new RegExp('pattern', 'flags');
Common Methods
regex.test(str) // Returns boolean
str.match(regex) // Returns matches
str.replace(regex, replacement)
str.search(regex) // Returns index
Common Patterns
/\d+/One or more digits
/\w+/Word characters
/\s+/Whitespace
/^.+$/Start to end
/[a-z]/iCase insensitive
📋

JSON

JSON Methods
// Object to JSON string
const json = JSON.stringify(obj);
// JSON string to object
const obj = JSON.parse(json);
With Error Handling
try {
const data = JSON.parse(jsonString);
} catch (error) {
console.error('Invalid JSON', error);
}
Pretty Print
JSON.stringify(obj, null, 2) // Indented
🔢

Math & Numbers

Math Object
Math.random() // 0 to 1
Math.floor(4.7) // 4
Math.ceil(4.1) // 5
Math.round(4.5) // 5
Math.max(1, 2, 3) // 3
Math.min(1, 2, 3) // 1
Number Methods
Number.isInteger(42) // true
Number.isNaN(NaN) // true
Number.parseFloat('3.14') // 3.14
(42).toString(16) // '2a' (hex)
(3.14159).toFixed(2) // '3.14'
📅

Date & Time

Creating Dates
new Date() // Current date
new Date('2023-12-25')
new Date(2023, 11, 25) // Month is 0-based
Date.now() // Timestamp
Date Methods
date.getFullYear() // 2023
date.getMonth() // 0-11
date.getDate() // 1-31
date.getHours() // 0-23
date.toISOString() // ISO format
🧠

Advanced Concepts

Closures
function outer(x) {
return function inner(y) {
return x + y; // Access outer scope
};
}
const addFive = outer(5);
Prototypes
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
Generator Functions
function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator();
gen.next().value; // 1

JavaScript Cheatsheet • by @CodersStudy

Covers ES6+ features and modern JavaScript patterns