0% found this document useful (0 votes)
20 views48 pages

Javascript Cheetsheet

This JavaScript cheat sheet covers essential concepts including variable declarations, data types, operators, control flow, functions, objects, arrays, and ES6+ features. It provides syntax examples for various programming constructs such as loops, conditionals, and function expressions, along with methods for manipulating arrays and objects. Additionally, it includes information on promises, async/await, and DOM manipulation techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views48 pages

Javascript Cheetsheet

This JavaScript cheat sheet covers essential concepts including variable declarations, data types, operators, control flow, functions, objects, arrays, and ES6+ features. It provides syntax examples for various programming constructs such as loops, conditionals, and function expressions, along with methods for manipulating arrays and objects. Additionally, it includes information on promises, async/await, and DOM manipulation techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

JavaScript cheat Sheet

JavaScript Cheat Sheet


Basics
Variables
javascript

var x = 10; // Function-scoped, can be redeclared


let y = 20; // Block-scoped, cannot be redeclared
const z = 30; // Block-scoped, constant, cannot be reassigned

Data Types
Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt

Non-primitive: Object, Array, Function

javascript

typeof "Hello" // "string"


typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (historical bug)
typeof Symbol() // "symbol"
typeof 123n // "bigint"
typeof {} // "object"
typeof [] // "object"
typeof function() {} // "function"

Operators
javascript

JavaScript cheat Sheet 1


// Arithmetic
+ - * / % ** ++ --

// 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

Type Conversion & Coercion


javascript

// Explicit conversion
String(123) // "123"
Number("123") // 123
Boolean(1) // true
parseInt("10") // 10
parseFloat("10.5") // 10.5

// Implicit coercion (type coercion)


"5" + 2 // "52" (string concatenation)

JavaScript cheat Sheet 2


"5" - 2 // 3 (numeric subtraction)
"5" * "2" // 10 (numeric multiplication)

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

JavaScript cheat Sheet 3


// For loop
for (let i = 0; i < 5; i++) {
// code
}

// While loop
while (condition) {
// code
}

// Do-while loop
do {
// code
} while (condition);

// For...of loop (arrays, strings, maps, sets)


for (const item of array) {
// code
}

// For...in loop (object properties)


for (const key in object) {
// code
}

// forEach (arrays only)


array.forEach((item, index) => {
// code
});

Functions
Function Declarations
javascript

JavaScript cheat Sheet 4


function greet(name) {
return `Hello ${name}`;
}

Function Expressions
javascript

const greet = function(name) {


return `Hello ${name}`;
};

Arrow Functions
javascript

const greet = (name) => {


return `Hello ${name}`;
};

// Implicit return
const greet = name => `Hello ${name}`;

// No parameters
const sayHello = () => console.log("Hello");

Default Parameters
javascript

function greet(name = "Guest") {


return `Hello ${name}`;
}

Rest Parameters

JavaScript cheat Sheet 5


javascript

function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}

IIFE (Immediately Invoked Function Expression)


javascript

(function() {
// code
})();

(() => {
// code
})();

Higher-Order Functions
javascript

// Functions that take other functions as arguments


function operateOnArray(arr, operation) {
return arr.map(operation);
}

// Functions that return functions


function multiplier(factor) {
return function(x) {
return x * factor;
};
}

Closures

JavaScript cheat Sheet 6


javascript

function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}

const counter = createCounter();


counter(); // 1
counter(); // 2

Currying
javascript

// Transforming a function with multiple arguments into a sequence of functio


ns
function multiply(a) {
return function(b) {
return a * b;
};
}

// Using arrow functions


const multiply = a => b => a * b;

multiply(2)(3); // 6

Objects & Arrays


Object Creation
javascript

JavaScript cheat Sheet 7


// Object literal
const obj = {
property: "value",
method() {
return this.property;
}
};

// 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];

JavaScript cheat Sheet 8


// Constructor
const arr = new Array(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;

// Function parameter destructuring


function greet({ name, age }) {
return `Hello ${name}, you are ${age} years old`;
}

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 };

JavaScript cheat Sheet 9


const merged = { ...obj1, ...obj2 };

// Rest (function parameters)


function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}

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

JavaScript cheat Sheet 10


// Ordering
sort() // sorts array elements
reverse() // reverses array order

// Other
concat() // merges arrays
join() // joins array elements into string

Object Methods
javascript

Object.keys(obj) // returns array of keys


Object.values(obj) // returns array of values
Object.entries(obj) // returns array of key-value pairs
Object.assign(target, source) // copies properties from source to target
Object.freeze(obj) // prevents modification of object
Object.seal(obj) // prevents adding/removing properties
Object.create(proto) // creates object with specified prototype

Sets
javascript

const set = new Set([1, 2, 3, 3, 4]); // {1, 2, 3, 4}

set.add(5) // adds value


set.delete(1) // removes value
set.has(2) // checks if value exists
set.size // returns number of values
set.clear() // removes all values

// Iteration
for (const item of set) {

JavaScript cheat Sheet 11


console.log(item);
}

Maps
javascript

const map = new Map();


map.set('key', 'value'); // adds key-value pair
map.get('key'); // returns value for key
map.has('key'); // checks if key exists
map.delete('key'); // removes key-value pair
map.size // returns number of entries
map.clear() // removes all entries

// Iteration
for (const [key, value] of map) {
console.log(key, value);
}

WeakMap and WeakSet


javascript

// WeakMap (keys must be objects, not iterable, automatically cleans up unus


ed references)
const weakMap = new WeakMap();
const keyObj = {};
weakMap.set(keyObj, 'value');

// WeakSet (values must be objects, not iterable, automatically cleans up unus


ed references)
const weakSet = new WeakSet();
const obj = {};
weakSet.add(obj);

JavaScript cheat Sheet 12


Strings & Numbers
String Methods
javascript

// 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

// Splitting & Joining


split(separator) // splits string into array by separator
concat(str1, str2) // concatenates strings

// Pattern Matching
match(regexp) // returns array of matches

JavaScript cheat Sheet 13


matchAll(regexp) // returns iterator of all matches
search(regexp) // returns index of first match

Template Literals
javascript

const name = "John";


const message = `Hello ${name}!
Welcome to JavaScript.`; // Multi-line string

// Tagged templates
function tag(strings, ...values) {
return strings.reduce((result, string, i) =>
`${result}${string}${values[i] || ''}`, '');
}

BigInt
javascript

const bigInt = 123456789012345678901234567890n;


const alsoBigInt = BigInt("123456789012345678901234567890");

// Operations
bigInt + 1n // 123456789012345678901234567891n
bigInt * 2n // 246913578024691357802469135780n

// Cannot mix with Number


// bigInt + 1 // TypeError

Math Methods
javascript

JavaScript cheat Sheet 14


Math.abs(x) // absolute value
Math.ceil(x) // rounds up to nearest integer
Math.floor(x) // rounds down to nearest integer
Math.round(x) // rounds to nearest integer
Math.max(...values) // returns largest of zero or more numbers
Math.min(...values) // returns smallest of zero or more numbers
Math.random() // returns random number between 0 and 1
Math.pow(x, y) // returns x to the power of y
Math.sqrt(x) // square root of x
Math.trunc(x) // returns integer part of x

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}`;

JavaScript cheat Sheet 15


}

// Static method
static species() {
return 'Homo sapiens';
}
}

class Developer extends Person {


constructor(name, language) {
super(name);
this.language = language;
}

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

JavaScript cheat Sheet 16


javascript

const promise = new Promise((resolve, reject) => {


// Async operation
if (success) {
resolve(value);
} else {
reject(error);
}
});

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

async function fetchData() {


try {
const response = await fetch('https://api.example.com/data');

JavaScript cheat Sheet 17


const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}

Optional Chaining
javascript

const name = user?.profile?.name; // returns undefined if any part is null/unde


fined
const result = obj.method?.(); // safe method call

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

JavaScript cheat Sheet 18


Events
javascript

// Adding event listeners


element.addEventListener('click', handler);
element.onclick = handler; // not recommended

// Removing event listeners


element.removeEventListener('click', handler);

// Event object properties


event.target // element that triggered event
event.currentTarget // element that has the event handler
event.type // event type ('click', etc.)
event.preventDefault() // prevents default behavior
event.stopPropagation() // stops event bubbling

Event Bubbling/Capturing
javascript

// Event flow: Capturing -> Target -> Bubbling


element.addEventListener('click', handler, true); // capturing phase
element.addEventListener('click', handler, false); // bubbling phase (default)

The this Context


In event handlers, this refers to the element that received the event.

Forms
javascript

// Accessing form elements


const form = document.forms['formName'];
const input = form.elements['inputName'];

JavaScript cheat Sheet 19


// Form events
form.addEventListener('submit', event => {
event.preventDefault(); // prevent form submission
const formData = new FormData(form);
// process form data
});

// 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';

JavaScript cheat Sheet 20


// CSS classes
element.classList.add('class');
element.classList.remove('class');
element.classList.toggle('class');
element.classList.contains('class');

// Computed styles
getComputedStyle(element).property;

Events & Browser APIs


addEventListener
javascript

element.addEventListener(type, listener, options);


// options: { once: true, capture: true, passive: true }

Timers
javascript

// setTimeout - executes once after delay


const timeoutId = setTimeout(() => {
// code
}, 1000);

// clearTimeout
clearTimeout(timeoutId);

// setInterval - executes repeatedly with delay


const intervalId = setInterval(() => {
// code
}, 1000);

JavaScript cheat Sheet 21


// clearInterval
clearInterval(intervalId);

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

// localStorage - persists until explicitly cleared


localStorage.setItem('key', 'value');
const value = localStorage.getItem('key');
localStorage.removeItem('key');

JavaScript cheat Sheet 22


localStorage.clear();

// sessionStorage - persists only for session


sessionStorage.setItem('key', 'value');
const value = sessionStorage.getItem('key');
sessionStorage.removeItem('key');
sessionStorage.clear();

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
},

JavaScript cheat Sheet 23


error => {
// handle error
},
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 60000
}
);

WebSockets
javascript

const socket = new WebSocket('wss://echo.websocket.org');

socket.onopen = event => {


socket.send('Hello Server!');
};

socket.onmessage = event => {


console.log('Message from server:', event.data);
};

socket.onclose = event => {


console.log('Connection closed');
};

socket.onerror = error => {


console.error('WebSocket error:', error);
};

Asynchronous JavaScript
Callbacks

JavaScript cheat Sheet 24


javascript

function fetchData(callback) {
// Async operation
setTimeout(() => {
callback(null, data); // Node.js convention: error first
}, 1000);
}

fetchData((error, data) => {


if (error) {
// handle error
} else {
// process data
}
});

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:

1. Call Stack: Where function calls form a stack of frames

2. Heap: Objects are allocated in a heap

3. Queue: Messages are queued for processing

Microtasks vs Macrotasks
javascript

JavaScript cheat Sheet 25


// Microtasks (higher priority): Promise callbacks, queueMicrotask, MutationO
bserver
// Macrotasks: setTimeout, setInterval, setImmediate, I/O, UI rendering

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

JavaScript cheat Sheet 26


riskyOperation();
} catch (error) {
// handle error
console.error('An error occurred:', error.message);
} finally {
// always executes
cleanup();
}

Custom Errors
javascript

class ValidationError extends Error {


constructor(message) {
super(message);
this.name = 'ValidationError';
}
}

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

JavaScript cheat Sheet 27


console.warn('Warning'); // warning message
console.error('Error'); // error message
console.table(data); // tabular data display
console.group('Group'); // groups messages
console.groupEnd(); // ends group
console.time('Timer'); // starts timer
console.timeEnd('Timer'); // ends timer and logs duration
console.trace(); // stack trace

Object-Oriented JavaScript
Prototypes
javascript

// Every object has a prototype from which it inherits properties


function Person(name) {
this.name = name;
}

Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};

const person = new Person('John');


person.greet(); // "Hello, I'm John"

Inheritance
javascript

// Constructor inheritance
function Employee(name, title) {
Person.call(this, name); // call parent constructor
this.title = title;
}

JavaScript cheat Sheet 28


// Prototype inheritance
Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;

// Method overriding
Employee.prototype.greet = function() {
return `Hello, I'm ${this.name}, ${this.title}`;
};

Classes
As shown in the ES6+ section.

The this Keyword


javascript

// In methods: refers to the object


// In functions: depends on how function is called
// In arrow functions: lexically bound (value of this in enclosing scope)
// In event handlers: refers to the element that received the event

bind/call/apply
javascript

function greet(greeting, punctuation) {


return `${greeting}, ${this.name}${punctuation}`;
}

const person = { name: 'John' };

// bind - returns a new function with this bound to context


const boundGreet = greet.bind(person);
boundGreet('Hello', '!'); // "Hello, John!"

JavaScript cheat Sheet 29


// call - calls function with this set to context and individual arguments
greet.call(person, 'Hello', '!'); // "Hello, John!"

// apply - calls function with this set to context and array of arguments
greet.apply(person, ['Hello', '!']); // "Hello, John!"

Encapsulation
javascript

// Using closures for private members


function createCounter() {
let count = 0; // private variable

return {
increment() {
count++;
},
getValue() {
return count;
}
};
}

// Using classes with private fields (ES2022)


class Counter {
#count = 0; // private field

increment() {
this.#count++;
}

getValue() {
return this.#count;

JavaScript cheat Sheet 30


}
}

Functional Programming
map
javascript

// Creates new array by applying function to each element


const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2); // [2, 4, 6]

filter
javascript

// Creates new array with elements that pass test


const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(x => x % 2 === 0); // [2, 4]

reduce
javascript

// Reduces array to single value


const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, current) => accumulator + curren
t, 0); // 10

// More complex example


const people = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];

JavaScript cheat Sheet 31


const ageSum = people.reduce((acc, person) => acc + person.age, 0); // 90

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

// Working with data without modifying original


const original = [1, 2, 3];

// Instead of modifying original array


// original.push(4); // MUTATION

// Create new array with added element


const updated = [...original, 4]; // [1, 2, 3, 4]

// For objects
const originalObj = { a: 1, b: 2 };
const updatedObj = { ...originalObj, c: 3 }; // { a: 1, b: 2, c: 3 }

JavaScript cheat Sheet 32


Advanced Concepts
Hoisting
javascript

// Variable hoisting (var declarations are hoisted, not initializations)


console.log(x); // undefined
var x = 5;
console.log(x); // 5

// Function declarations are fully hoisted


foo(); // "Hello"
function foo() {
console.log("Hello");
}

// let/const are hoisted but not initialized (Temporal Dead Zone)


console.log(y); // ReferenceError
let y = 5;

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

JavaScript cheat Sheet 33


console.log(functionVar); // 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.

Memory Management & Garbage Collection


JavaScript uses automatic garbage collection (mark-and-sweep algorithm).

Modules & Package Management


ES Modules
javascript

// Exporting (math.js)
export const pi = 3.14159;
export function square(x) { return x * x; }

JavaScript cheat Sheet 34


export default function multiply(a, b) { return a * b; }

// 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

JavaScript cheat Sheet 35


# Run scripts
npm run script-name

Performance Optimization
Debouncing
javascript

function debounce(func, delay) {


let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(this, args), delay);
};
}

// Usage
const handleInput = debounce((value) => {
// process input
}, 300);

input.addEventListener('input', (e) => handleInput(e.target.value));

Throttling
javascript

function throttle(func, delay) {


let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
return func.apply(this, args);

JavaScript cheat Sheet 36


};
}

// 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

JavaScript cheat Sheet 37


// For images
const lazyImages = document.querySelectorAll('img[data-src]');

const lazyLoad = (image) => {


image.setAttribute('src', image.getAttribute('data-src'));
image.onload = () => {
image.removeAttribute('data-src');
};
};

const intersectionObserver = new IntersectionObserver((entries, observer) =>


{
entries.forEach(entry => {
if (entry.isIntersecting) {
lazyLoad(entry.target);
observer.unobserve(entry.target);
}
});
});

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

JavaScript cheat Sheet 38


// Instead of adding event listeners to each element
// Add a single event listener to a parent element
document.getElementById('list').addEventListener('click', event => {
if (event.target.tagName === 'LI') {
// handle list item click
console.log('Clicked on:', event.target.textContent);
}
});

Shallow vs Deep Copy


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)

// Alternative deep copy (with limitations)


const deepCopy2 = structuredClone(original);

JSON Methods
javascript

const obj = { name: 'John', age: 30 };

// Convert to JSON string

JavaScript cheat Sheet 39


const jsonString = JSON.stringify(obj); // '{"name":"John","age":30}'

// Parse JSON string


const parsedObj = JSON.parse(jsonString); // { name: 'John', age: 30 }

// With replacer and reviver functions


const withReplacer = JSON.stringify(obj, (key, value) => {
if (key === 'age') return undefined; // exclude age
return value;
}); // '{"name":"John"}'

const withReviver = JSON.parse('{"name":"John","age":30}', (key, value) => {


if (key === 'age') return value + 1; // increment age
return value;
}); // { name: 'John', age: 31 }

Working with APIs


javascript

// Using fetch with error handling


async function fetchData(url) {
try {
const response = await fetch(url);

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();


return data;
} catch (error) {
console.error('Failed to fetch data:', error);
throw error;
}
}

JavaScript cheat Sheet 40


// Using with retry logic
async function fetchWithRetry(url, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await fetchData(url);
} catch (error) {
if (i === retries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}

Modern Features
Generators
javascript

function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}

const generator = numberGenerator();


console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }

// Using for...of with generators


for (const num of numberGenerator()) {
console.log(num); // 1, 2, 3
}

JavaScript cheat Sheet 41


Async Iterators
javascript

async function* asyncNumberGenerator() {


for (let i = 0; i < 3; i++) {
await new Promise(resolve => setTimeout(resolve, 100));
yield i;
}
}

(async () => {
for await (const num of asyncNumberGenerator()) {
console.log(num); // 0, 1, 2 (with 100ms delay between each)
}
})();

Symbols
javascript

// Unique and immutable primitive value


const sym1 = Symbol('description');
const sym2 = Symbol('description');
console.log(sym1 === sym2); // false

// Used as object property keys


const obj = {
[sym1]: 'value1',
[sym2]: 'value2'
};

// Well-known symbols
Symbol.iterator; // makes an object iterable
Symbol.asyncIterator; // makes an object async iterable
Symbol.toStringTag; // customizes Object.prototype.toString()

JavaScript cheat Sheet 42


Proxies
javascript

// Create wrappers around objects


const target = {};
const handler = {
get(obj, prop) {
return prop in obj ? obj[prop] : 'default';
},
set(obj, prop, value) {
if (prop === 'age' && typeof value !== 'number') {
throw new TypeError('Age must be a number');
}
obj[prop] = value;
return true;
}
};

const proxy = new Proxy(target, handler);


proxy.name = 'John';
console.log(proxy.name); // 'John'
console.log(proxy.unknown); // 'default'

Reflect API
javascript

// Provides methods for interceptable JavaScript operations


const obj = { a: 1 };

// Instead of: 'a' in obj


Reflect.has(obj, 'a'); // true

// Instead of: delete obj.a


Reflect.deleteProperty(obj, 'a'); // true

JavaScript cheat Sheet 43


// Instead of: Object.getOwnPropertyDescriptor(obj, 'a')
Reflect.getOwnPropertyDescriptor(obj, 'a');

// Instead of: Object.defineProperty(obj, 'b', { value: 2 })


Reflect.defineProperty(obj, 'b', { value: 2 });

Best Practices & Patterns


DRY (Don't Repeat Yourself)
Avoid code duplication by abstracting common functionality.

KISS (Keep It Simple, Stupid)


Favor simplicity over complexity.

SOLID Principles
Single Responsibility: A class should have only one reason to change

Open/Closed: Open for extension, closed for modification

Liskov Substitution: Subtypes must be substitutable for their base types

Interface Segregation: Many specific interfaces are better than one general
interface

Dependency Inversion: Depend on abstractions, not concretions

Design Patterns

Singleton
javascript

class Singleton {
static instance;

constructor() {

JavaScript cheat Sheet 44


if (Singleton.instance) {
return Singleton.instance;
}
Singleton.instance = this;
}
}

Module
javascript

const MyModule = (function() {


let privateVar = 'private';

function privateMethod() {
return privateVar;
}

return {
publicMethod() {
return privateMethod();
}
};
})();

Observer
javascript

class Observable {
constructor() {
this.observers = [];
}

subscribe(observer) {
this.observers.push(observer);

JavaScript cheat Sheet 45


}

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);
}
}

const factory = new CarFactory();


const car = factory.createCar('Toyota', 'Camry');

Interview Prep - Common Tricky Questions


Event Loop Questions
javascript

JavaScript cheat Sheet 46


console.log('Start');

setTimeout(() => console.log('Timeout'), 0);

Promise.resolve()
.then(() => console.log('Promise'));

console.log('End');

// Output order:
// Start
// End
// Promise
// Timeout

Closures Questions
javascript

for (var i = 0; i < 3; i++) {


setTimeout(() => console.log(i), 100);
}
// Output: 3, 3, 3 (because var is function-scoped)

// Fix with IIFE or let


for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// Output: 0, 1, 2 (because let is block-scoped)

this Questions
javascript

JavaScript cheat Sheet 47


const obj = {
value: 'a',
method: function() {
console.log(this.value);
},
arrowMethod: () => {
console.log(this.value);
}
};

obj.method(); // 'a' (this refers to obj)


obj.arrowMethod(); // undefined (this refers to global/window)

const extracted = obj.method;


extracted(); // undefined (this refers to global/window)

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));

// Output: 4 (error is caught and recovery continues)

This comprehensive cheatsheet covers JavaScript from basic to advanced


concepts, providing a solid reference for developers at all levels.

JavaScript cheat Sheet 48

You might also like