Javascript Cheetsheet
Javascript Cheetsheet
Data Types
Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt
javascript
Operators
javascript
// Assignment
= += -= *= /= %= **=
// Comparison
== != === !== > < >= <=
// Logical
&& || !
// Ternary
condition ? expr1 : expr2
// Nullish Coalescing
?? // returns right operand if left is null/undefined
// Optional Chaining
?. // returns undefined if reference is null/undefined
// Explicit conversion
String(123) // "123"
Number("123") // 123
Boolean(1) // true
parseInt("10") // 10
parseFloat("10.5") // 10.5
Control Flow
If/Else
javascript
if (condition) {
// code
} else if (anotherCondition) {
// code
} else {
// code
}
Switch
javascript
switch(expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// code
}
Loops
javascript
// While loop
while (condition) {
// code
}
// Do-while loop
do {
// code
} while (condition);
Functions
Function Declarations
javascript
Function Expressions
javascript
Arrow Functions
javascript
// Implicit return
const greet = name => `Hello ${name}`;
// No parameters
const sayHello = () => console.log("Hello");
Default Parameters
javascript
Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
(function() {
// code
})();
(() => {
// code
})();
Higher-Order Functions
javascript
Closures
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
Currying
javascript
multiply(2)(3); // 6
// Constructor function
function Person(name) {
this.name = name;
}
// Class syntax
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, I'm ${this.name}`;
}
}
// Object.create()
const prototypeObj = { greet() { return "Hello"; } };
const obj = Object.create(prototypeObj);
Array Creation
javascript
// Array literal
const arr = [1, 2, 3];
// Array.of()
const arr = Array.of(1, 2, 3);
// Array.from()
const arr = Array.from("hello"); // ['h', 'e', 'l', 'l', 'o']
Destructuring
javascript
// Array destructuring
const [a, b, ...rest] = [1, 2, 3, 4, 5];
// Object destructuring
const { name, age, ...details } = person;
Spread/Rest Operator
javascript
// Spread (arrays)
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
// Spread (objects)
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
Array Methods
javascript
// Transformation
map() // creates new array with transformed elements
filter() // creates new array with elements that pass test
reduce() // reduces array to single value
flat() // flattens nested arrays
flatMap() // maps then flattens
// Iteration
forEach() // executes function for each element
some() // tests if at least one element passes test
every() // tests if all elements pass test
// Search
find() // returns first element that passes test
findIndex() // returns index of first element that passes test
includes() // checks if array contains value
// Manipulation
push() // adds elements to end
pop() // removes last element
shift() // removes first element
unshift() // adds elements to beginning
splice() // adds/removes elements at specific index
slice() // returns shallow copy of portion of array
// Other
concat() // merges arrays
join() // joins array elements into string
Object Methods
javascript
Sets
javascript
// Iteration
for (const item of set) {
Maps
javascript
// Iteration
for (const [key, value] of map) {
console.log(key, value);
}
// Access
charAt(index) // returns character at index
charCodeAt(index) // returns Unicode of character at index
at(index) // returns character at index (supports negative)
// Search
indexOf(search) // returns first index of search string
lastIndexOf(search) // returns last index of search string
includes(search) // checks if string contains search string
startsWith(search) // checks if string starts with search string
endsWith(search) // checks if string ends with search string
// Modification
slice(start, end) // extracts section of string
substring(start, end) // similar to slice but doesn't accept negative
substr(start, length) // extracts characters from start position
toUpperCase() // converts to uppercase
toLowerCase() // converts to lowercase
trim() // removes whitespace from both ends
replace(search, replace) // replaces search with replace
replaceAll(search, replace) // replaces all occurrences
// Pattern Matching
match(regexp) // returns array of matches
Template Literals
javascript
// Tagged templates
function tag(strings, ...values) {
return strings.reduce((result, string, i) =>
`${result}${string}${values[i] || ''}`, '');
}
BigInt
javascript
// Operations
bigInt + 1n // 123456789012345678901234567891n
bigInt * 2n // 246913578024691357802469135780n
Math Methods
javascript
ES6+ Features
let/const
Block-scoped variable declarations that prevent many common JS issues.
Arrow Functions
Concise syntax and lexical this binding.
Template Literals
String interpolation and multi-line strings.
Classes
javascript
class Person {
constructor(name) {
this.name = name;
}
// Instance method
greet() {
return `Hello, I'm ${this.name}`;
// Static method
static species() {
return 'Homo sapiens';
}
}
code() {
return `${this.name} codes in ${this.language}`;
}
}
Destructuring
Easily extract values from arrays or properties from objects.
Modules
javascript
// Exporting (module.js)
export const pi = 3.14159;
export function square(x) { return x * x; }
export default class Circle { /* ... */ }
// Importing (main.js)
import Circle, { pi, square } from './module.js';
Promises
promise
.then(result => {
// Handle success
})
.catch(error => {
// Handle error
})
.finally(() => {
// Always executes
});
// Promise methods
Promise.all([promise1, promise2]) // waits for all promises to resolve
Promise.allSettled([promise1, promise2]) // waits for all promises to settle
Promise.race([promise1, promise2]) // resolves/rejects with first settled pro
mise
Promise.any([promise1, promise2]) // resolves with first fulfilled promise
Async/Await
javascript
Optional Chaining
javascript
Nullish Coalescing
javascript
const value = input ?? 'default'; // returns right operand only if left is null or un
defined
DOM Manipulation
Selectors
javascript
document.getElementById('id');
document.getElementsByClassName('class');
document.getElementsByTagName('div');
document.querySelector('.class'); // returns first match
document.querySelectorAll('.class'); // returns NodeList of all matches
Event Bubbling/Capturing
javascript
Forms
javascript
// Form validation
input.addEventListener('input', event => {
if (!input.checkValidity()) {
input.setCustomValidity('Custom error message');
} else {
input.setCustomValidity('');
}
});
Attributes
javascript
element.getAttribute('attribute');
element.setAttribute('attribute', 'value');
element.removeAttribute('attribute');
element.hasAttribute('attribute');
// Data attributes
element.dataset.key; // access data-key attribute
Styles
javascript
// Inline styles
element.style.color = 'red';
element.style.backgroundColor = 'blue';
// Computed styles
getComputedStyle(element).property;
Timers
javascript
// clearTimeout
clearTimeout(timeoutId);
Fetch API
javascript
fetch('https://api.example.com/data', {
method: 'GET', // or 'POST', 'PUT', 'DELETE', etc.
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data), // for POST/PUT requests
credentials: 'include', // include cookies
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // or response.text(), response.blob(), etc.
})
.then(data => {
// process data
})
.catch(error => {
// handle error
});
Web Storage
javascript
Cookies
javascript
// Setting cookie
document.cookie = 'name=value; expires=Fri, 31 Dec 2023 23:59:59 GMT; pa
th=/';
// Getting cookie
const cookies = document.cookie.split('; ').reduce((acc, cookie) => {
const [name, value] = cookie.split('=');
acc[name] = value;
return acc;
}, {});
// Deleting cookie
document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path
=/';
Geolocation API
javascript
navigator.geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords;
// use location data
},
WebSockets
javascript
Asynchronous JavaScript
Callbacks
function fetchData(callback) {
// Async operation
setTimeout(() => {
callback(null, data); // Node.js convention: error first
}, 1000);
}
Promises
As shown in the ES6+ section.
Async/Await
As shown in the ES6+ section.
Event Loop
JavaScript has a concurrency model based on an event loop:
Microtasks vs Macrotasks
javascript
console.log('Script start');
setTimeout(() => {
console.log('setTimeout'); // macrotask
}, 0);
Promise.resolve()
.then(() => {
console.log('Promise 1'); // microtask
})
.then(() => {
console.log('Promise 2'); // microtask
});
console.log('Script end');
// Output order:
// Script start
// Script end
// Promise 1
// Promise 2
// setTimeout
Error Handling
try/catch/finally
javascript
try {
// code that may throw an error
Custom Errors
javascript
function validateInput(input) {
if (!input) {
throw new ValidationError('Input is required');
}
}
Debugging
javascript
// Debugger statement
debugger; // pauses execution if dev tools are open
// Console methods
console.log('Message'); // general logging
console.info('Information'); // informational message
Object-Oriented JavaScript
Prototypes
javascript
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
Inheritance
javascript
// Constructor inheritance
function Employee(name, title) {
Person.call(this, name); // call parent constructor
this.title = title;
}
// Method overriding
Employee.prototype.greet = function() {
return `Hello, I'm ${this.name}, ${this.title}`;
};
Classes
As shown in the ES6+ section.
bind/call/apply
javascript
// apply - calls function with this set to context and array of arguments
greet.apply(person, ['Hello', '!']); // "Hello, John!"
Encapsulation
javascript
return {
increment() {
count++;
},
getValue() {
return count;
}
};
}
increment() {
this.#count++;
}
getValue() {
return this.#count;
Functional Programming
map
javascript
filter
javascript
reduce
javascript
Pure Functions
javascript
// Functions that always return the same output for the same input
// and have no side effects
function add(a, b) {
return a + b; // pure function
}
let counter = 0;
function increment() {
counter++; // impure function (has side effect)
}
Immutability
javascript
// For objects
const originalObj = { a: 1, b: 2 };
const updatedObj = { ...originalObj, c: 3 }; // { a: 1, b: 2, c: 3 }
Scope
javascript
// Global scope
var globalVar = "I'm global";
function test() {
// Function scope
var functionVar = "I'm in function scope";
if (true) {
// Block scope (let/const)
let blockVar = "I'm in block scope";
console.log(globalVar); // accessible
console.log(blockVar); // ReferenceError
}
Closures
As shown in the Functions section.
Context
The value of this depends on how a function is called.
Execution Context
JavaScript code runs in execution contexts that have:
1. Variable environment
2. Scope chain
3. this value
Lexical Environment
Where code is physically written in the source code, determining scope.
// Exporting (math.js)
export const pi = 3.14159;
export function square(x) { return x * x; }
// Importing (app.js)
import multiply, { pi, square } from './math.js';
import * as math from './math.js'; // namespace import
CommonJS
javascript
// Exporting (math.js)
exports.pi = 3.14159;
exports.square = function(x) { return x * x; };
module.exports = function multiply(a, b) { return a * b; };
// Importing (app.js)
const multiply = require('./math.js');
const { pi, square } = require('./math.js');
npm Basics
bash
# Initialize package
npm init
# Install package
npm install package-name
npm install -D package-name # dev dependency
npm install -g package-name # global install
# Update package
npm update package-name
# Uninstall package
npm uninstall package-name
Performance Optimization
Debouncing
javascript
// Usage
const handleInput = debounce((value) => {
// process input
}, 300);
Throttling
javascript
// Usage
const handleScroll = throttle(() => {
// handle scroll
}, 100);
window.addEventListener('scroll', handleScroll);
Memoization
javascript
function memoize(func) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
};
}
// Usage
const expensiveCalculation = memoize((n) => {
// expensive calculation
return n * n;
});
Lazy Loading
javascript
lazyImages.forEach(image => {
intersectionObserver.observe(image);
});
Tree Shaking
Process of eliminating dead code from the final bundle. Works best with ES
modules.
JavaScript in Practice
Event Delegation
javascript
const original = { a: 1, b: { c: 2 } };
// Shallow copy
const shallowCopy = { ...original };
shallowCopy.b.c = 3;
console.log(original.b.c); // 3 (original is modified)
// Deep copy
const deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.b.c = 4;
console.log(original.b.c); // 3 (original is not modified)
JSON Methods
javascript
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
Modern Features
Generators
javascript
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
(async () => {
for await (const num of asyncNumberGenerator()) {
console.log(num); // 0, 1, 2 (with 100ms delay between each)
}
})();
Symbols
javascript
// Well-known symbols
Symbol.iterator; // makes an object iterable
Symbol.asyncIterator; // makes an object async iterable
Symbol.toStringTag; // customizes Object.prototype.toString()
Reflect API
javascript
SOLID Principles
Single Responsibility: A class should have only one reason to change
Interface Segregation: Many specific interfaces are better than one general
interface
Design Patterns
Singleton
javascript
class Singleton {
static instance;
constructor() {
Module
javascript
function privateMethod() {
return privateVar;
}
return {
publicMethod() {
return privateMethod();
}
};
})();
Observer
javascript
class Observable {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
notify(data) {
this.observers.forEach(observer => observer(data));
}
}
Factory
javascript
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
class CarFactory {
createCar(make, model) {
return new Car(make, model);
}
}
Promise.resolve()
.then(() => console.log('Promise'));
console.log('End');
// Output order:
// Start
// End
// Promise
// Timeout
Closures Questions
javascript
this Questions
javascript
Promises Questions
javascript
Promise.resolve(1)
.then(x => x + 1)
.then(x => { throw new Error('Error!') })
.catch(err => { return 3 })
.then(x => x + 1)
.then(x => console.log(x))
.catch(err => console.error(err));