# [ The Ultimate JavaScript CheatSheet ]
1. Variables and Data Types
● Declare a variable: let x;
● Declare and initialize a variable: let x = 5;
● Declare a constant: const PI = 3.14159;
● Declare a variable with block scope: let x = 10;
● Declare a variable with function scope: var y = 20;
● Number: let num = 42;
● String: let str = "Hello, World!";
● Boolean: let isTrue = true;
● Undefined: let x;
● Null: let y = null;
● Symbol: let sym = Symbol("description");
● BigInt: let bigNum = 1234567890123456789012345678901234567890n;
● Object: let obj = {key: "value"};
● Array: let arr = [1, 2, 3];
● Function: let func = function() {};
● Check type of variable: typeof variable
● Check if variable is an array: [Link](variable)
● Convert to number: Number(value)
● Convert to string: String(value)
● Convert to boolean: Boolean(value)
● Parse integer: parseInt("42")
● Parse float: parseFloat("3.14")
● Check if value is NaN: isNaN(value)
● Check if value is finite: isFinite(value)
● Get positive infinity: Infinity
● Get negative infinity: -Infinity
2. Operators
● Addition: let sum = a + b;
● Subtraction: let diff = a - b;
● Multiplication: let product = a * b;
● Division: let quotient = a / b;
● Modulus: let remainder = a % b;
● Exponentiation: let power = a ** b;
● Increment: x++; or ++x;
By: Waleed Mousa
● Decrement: x--; or --x;
● Unary plus: let num = +x;
● Unary negation: let negNum = -x;
● Logical AND: let result = a && b;
● Logical OR: let result = a || b;
● Logical NOT: let result = !a;
● Nullish coalescing: let result = a ?? b;
● Optional chaining: let value = obj?.prop?.method?.();
● Equality: let isEqual = a == b;
● Strict equality: let isStrictEqual = a === b;
● Inequality: let isNotEqual = a != b;
● Strict inequality: let isStrictNotEqual = a !== b;
● Greater than: let isGreater = a > b;
● Less than: let isLess = a < b;
● Greater than or equal: let isGreaterOrEqual = a >= b;
● Less than or equal: let isLessOrEqual = a <= b;
● Ternary operator: let result = condition ? trueValue : falseValue;
● Bitwise AND: let result = a & b;
● Bitwise OR: let result = a | b;
● Bitwise XOR: let result = a ^ b;
● Bitwise NOT: let result = ~a;
● Left shift: let result = a << b;
● Sign-propagating right shift: let result = a >> b;
● Zero-fill right shift: let result = a >>> b;
● Assignment: x = y
● Addition assignment: x += y
● Subtraction assignment: x -= y
● Multiplication assignment: x *= y
● Division assignment: x /= y
● Remainder assignment: x %= y
● Exponentiation assignment: x **= y
● Left shift assignment: x <<= y
● Right shift assignment: x >>= y
● Unsigned right shift assignment: x >>>= y
● Bitwise AND assignment: x &= y
● Bitwise XOR assignment: x ^= y
● Bitwise OR assignment: x |= y
● Logical AND assignment: x &&= y
● Logical OR assignment: x ||= y
● Nullish coalescing assignment: x ??= y
By: Waleed Mousa
3. Control Flow
● If statement: if (condition) { }
● If-else statement: if (condition) { } else { }
● If-else if-else statement: if (condition1) { } else if (condition2) {
} else { }
● Switch statement:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
● For loop: for (let i = 0; i < 10; i++) { }
● While loop: while (condition) { }
● Do-while loop: do { } while (condition);
● For...in loop (objects): for (let key in object) { }
● For...of loop (iterables): for (let value of iterable) { }
● Break statement: break;
● Continue statement: continue;
● Labeled statement: label: statement
● Try-catch: try { } catch (error) { }
● Try-catch-finally: try { } catch (error) { } finally { }
● Throw an error: throw new Error("message");
● Conditional (ternary) operator: condition ? expr1 : expr2
● Short-circuit evaluation: expr1 && expr2
● Nullish coalescing operator: expr1 ?? expr2
● Optional chaining: obj?.prop?.method?.()
4. Functions
● Function declaration: function name(params) { }
● Function expression: let func = function(params) { };
● Arrow function: let func = (params) => { };
● Immediately Invoked Function Expression (IIFE): (function() { })();
● Function with default parameters: function name(param = defaultValue)
{ }
By: Waleed Mousa
● Rest parameters: function name(...args) { }
● Spread operator in function call: func(...array);
● Closure: function outer() { let x = 10; return function inner() {
return x; }; }
● Currying: let curriedFunc = a => b => a + b;
● Generator function: function* generator() { yield 1; yield 2; }
● Async function: async function name() { }
● Function as object property: let obj = { method() { } };
● Getter: let obj = { get propName() { } };
● Setter: let obj = { set propName(value) { } };
● Bind method: let boundFunc = [Link](thisArg, arg1, arg2);
● Call method: [Link](thisArg, arg1, arg2);
● Apply method: [Link](thisArg, [arg1, arg2]);
● Function length property: [Link]
● Function name property: [Link]
● Check if value is function: typeof value === 'function'
● Higher-order function: function higherOrder(callback) { callback(); }
● Pure function: function pure(x) { return x * 2; }
● Recursive function: function factorial(n) { return n <= 1 ? 1 : n *
factorial(n - 1); }
● Memoization: javascript function memoize(fn) { const cache = {};
return function(...args) { const key = [Link](args); if
(key in cache) { return cache[key]; } const result = [Link](this,
args); cache[key] = result; return result; } }
5. Objects
● Object literal: let obj = {key: "value"};
● Accessing object properties (dot notation): [Link]
● Accessing object properties (bracket notation): obj["key"]
● Adding a property: [Link] = "value";
● Deleting a property: delete [Link];
● [Link](): let keys = [Link](obj);
● [Link](): let values = [Link](obj);
● [Link](): let entries = [Link](obj);
● Object destructuring: let {key1, key2} = obj;
● Shallow clone object: let clone = {...obj};
● Deep clone object: let clone = [Link]([Link](obj));
● Merge objects: let merged = {...obj1, ...obj2};
● [Link](): [Link](obj);
By: Waleed Mousa
● [Link](): [Link](obj);
● [Link](): let isSame = [Link](value1, value2);
● Create object with prototype: let obj = [Link](protoObj);
● Get object prototype: [Link](obj);
● Set object prototype: [Link](obj, protoObj);
● Define property: [Link](obj, 'key', { value: 42,
writable: false });
● Define multiple properties: [Link](obj, { prop1: {},
prop2: {} });
● Get property descriptor: [Link](obj, 'key');
● Get all property descriptors: [Link](obj);
● Prevent extensions: [Link](obj);
● Check if object is extensible: [Link](obj);
● Check if object is sealed: [Link](obj);
● Check if object is frozen: [Link](obj);
● Get own property names: [Link](obj);
● Get own property symbols: [Link](obj);
● Check if object has property: [Link]('key')
● Object method shorthand: let obj = { method() { } };
● Computed property names: let obj = { [expression]: value };
● [Link](): let assigned = [Link](target, source1,
source2);
● [Link](): let obj = [Link]([['key1',
'value1'], ['key2', 'value2']]);
6. Arrays
● Array literal: let arr = [1, 2, 3];
● Array constructor: let arr = new Array(1, 2, 3);
● Accessing array elements: let element = arr[0];
● Setting array elements: arr[0] = 10;
● Array length: let length = [Link];
● Push element to array: [Link](element);
● Pop element from array: let lastElement = [Link]();
● Unshift element to array: [Link](element);
● Shift element from array: let firstElement = [Link]();
● Slice array: let subArray = [Link](start, end);
● Splice array: [Link](start, deleteCount, item1, item2, ...);
● Join array elements: let str = [Link](separator);
● Reverse array: [Link]();
By: Waleed Mousa
● Sort array: [Link]((a, b) => a - b);
● Find element in array: let found = [Link](element => condition);
● Find index of element: let index = [Link](element =>
condition);
● Filter array: let filtered = [Link](element => condition);
● Map array: let mapped = [Link](element => transformation);
● Reduce array: let result = [Link]((accumulator, currentValue) =>
operation, initialValue);
● Reduce array right-to-left: let result = [Link]((accumulator,
currentValue) => operation, initialValue);
● Every (all elements satisfy condition): let allSatisfy =
[Link](element => condition);
● Some (at least one element satisfies condition): let someSatisfy =
[Link](element => condition);
● ForEach: [Link](element => operation);
● Includes: let includes = [Link](element);
● IndexOf: let index = [Link](element);
● LastIndexOf: let lastIndex = [Link](element);
● Fill array: [Link](value, start, end);
● Flatten array: let flattened = [Link](depth);
● FlatMap: let flatMapped = [Link](element => operation);
● Array from iterable: let arrFromIterable = [Link](iterable);
● [Link]: let arr = [Link](1, 2, 3);
● [Link]: let isArray = [Link](arr);
● Spread operator: let newArr = [...arr];
● Destructuring assignment: let [a, b, ...rest] = arr;
● Concat arrays: let newArr = [Link](arr2, arr3);
● Copying array: let copy = [Link]();
● Clear array: [Link] = 0;
● Remove falsy values: arr = [Link](Boolean);
● Get unique values: let unique = [...new Set(arr)];
● Get max value: let max = [Link](...arr);
● Get min value: let min = [Link](...arr);
● Sum of array: let sum = [Link]((a, b) => a + b, 0);
● Average of array: let avg = [Link]((a, b) => a + b, 0) /
[Link];
● Shuffle array: [Link](() => [Link]() - 0.5);
● Check if array is empty: [Link] === 0
● Create array of numbers: let numbers = [Link]({length: 5}, (_, i)
=> i + 1);
By: Waleed Mousa
7. Strings
● String literal: let str = "Hello, World!";
● String object: let strObj = new String("Hello");
● String length: let length = [Link];
● Accessing characters: let char = str[0];
● Substring: let sub = [Link](start, end);
● Slice string: let sliced = [Link](start, end);
● Split string: let arr = [Link](separator);
● Concatenate strings: let newStr = [Link](str2);
● Trim whitespace: let trimmed = [Link]();
● Trim start: let trimmedStart = [Link]();
● Trim end: let trimmedEnd = [Link]();
● To uppercase: let upper = [Link]();
● To lowercase: let lower = [Link]();
● Replace: let replaced = [Link](searchValue, replaceValue);
● Replace all: let replacedAll = [Link](searchValue,
replaceValue);
● Includes: let includes = [Link](searchString);
● StartsWith: let startsWith = [Link](searchString);
● EndsWith: let endsWith = [Link](searchString);
● IndexOf: let index = [Link](searchString);
● LastIndexOf: let lastIndex = [Link](searchString);
● Char at index: let char = [Link](index);
● Char code at index: let charCode = [Link](index);
● Repeat string: let repeated = [Link](count);
● Pad start: let padded = [Link](targetLength, padString);
● Pad end: let padded = [Link](targetLength, padString);
● Match: let matches = [Link](regexp);
● Match all: let matchesIterator = [Link](regexp);
● Search: let index = [Link](regexp);
● LocaleCompare: let result = [Link](str2);
● FromCharCode: let str = [Link](65, 66, 67);
● FromCodePoint: let str = [Link](65, 66, 67);
● Raw: let raw = [Link];
● Normalize: let normalized = [Link]();
● Template literals: let greeting = `Hello, ${name}!`;
● Tagged template literals: function tag(strings, ...values) { }
By: Waleed Mousa
8. ES6+ Features
● Let and const: let x = 5; const y = 10;
● Arrow functions: let add = (a, b) => a + b;
● Default parameters: function greet(name = "World") { }
● Rest parameters: function sum(...numbers) { }
● Spread operator (array): let newArr = [...arr1, ...arr2];
● Spread operator (object): let newObj = {...obj1, ...obj2};
● Destructuring assignment (array): let [a, b] = [1, 2];
● Destructuring assignment (object): let {x, y} = {x: 1, y: 2};
● Enhanced object literals: let obj = {x, y, method() {}};
● Template literals: let greeting = `Hello, ${name}!`;
● Multi-line strings: let multiline = `Line 1 Line 2`;
● Symbol: let sym = Symbol("description");
● Iterators: let iterator = arr[[Link]]();
● Generators: function* generator() { yield 1; yield 2; }
● Promise: let promise = new Promise((resolve, reject) => { });
● Async/Await: async function fetchData() { let response = await
fetch(url); }
● Map: let map = new Map();
● Set: let set = new Set();
● WeakMap: let weakMap = new WeakMap();
● WeakSet: let weakSet = new WeakSet();
● Classes: class ClassName { constructor() {} }
● Class inheritance: class Child extends Parent { }
● Static methods: static methodName() { }
● Getters and setters: get propertyName() { } and set
propertyName(value) { }
● Modules (export): export { name1, name2 };
● Modules (import): import { name1, name2 } from "./[Link]";
● Default export: export default expression;
● Default import: import defaultExport from "./[Link]";
● Dynamic import: import("./[Link]").then(module => { });
● [Link](): [Link](target, source1, source2);
● [Link](): [Link](value1, value2);
● [Link](): [Link](arrayLike, mapFn, thisArg);
● [Link](): [Link](1, 2, 3);
● [Link](): "abc".repeat(3);
● [Link](): "Hello".startsWith("He");
● [Link](): "World".endsWith("ld");
By: Waleed Mousa
● [Link](): "Hello World".includes("Wor");
● [Link](): [Link](10);
● [Link](): [Link](NaN);
● [Link](): [Link](10);
● [Link]():
[Link](Number.MAX_SAFE_INTEGER);
● [Link](): [Link](4.9);
● [Link](): [Link](-10);
● [Link](): [Link](obj);
● [Link](): [Link](obj);
● [Link]():
[Link](obj);
● Trailing commas in function parameters: function f(a, b, ) { }
● Async iterators: for await (const x of asyncIterable) { }
● RegExp named capture groups:
/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
● RegExp lookbehind assertions: /(?<=\$)\d+(\.\d*)?/
9. DOM Manipulation
● Get element by ID: let element = [Link]("id");
● Get elements by class name: let elements =
[Link]("class");
● Get elements by tag name: let elements =
[Link]("tag");
● Query selector: let element = [Link]("selector");
● Query selector all: let elements =
[Link]("selector");
● Create element: let element = [Link]("tag");
● Create text node: let textNode = [Link]("text");
● Append child: [Link](child);
● Remove child: [Link](child);
● Replace child: [Link](newChild, oldChild);
● Insert before: [Link](newNode, referenceNode);
● Clone node: let clone = [Link](deep);
● Set attribute: [Link]("name", "value");
● Get attribute: let value = [Link]("name");
● Remove attribute: [Link]("name");
● Has attribute: let hasAttr = [Link]("name");
● Set inner HTML: [Link] = "content";
By: Waleed Mousa
● Get inner HTML: let content = [Link];
● Set text content: [Link] = "text";
● Get text content: let text = [Link];
● Add class: [Link]("class");
● Remove class: [Link]("class");
● Toggle class: [Link]("class");
● Check if has class: let hasClass =
[Link]("class");
● Set style: [Link] = "value";
● Get computed style: let style = getComputedStyle(element);
● Get bounding client rect: let rect = [Link]();
● Get offset width: let width = [Link];
● Get offset height: let height = [Link];
● Get client width: let width = [Link];
● Get client height: let height = [Link];
● Scroll into view: [Link](options);
● Focus element: [Link]();
● Blur element: [Link]();
● Get parent element: let parent = [Link];
● Get child elements: let children = [Link];
● Get first child element: let firstChild = [Link];
● Get last child element: let lastChild = [Link];
● Get next sibling element: let nextSibling =
[Link];
● Get previous sibling element: let prevSibling =
[Link];
10. Events
● Add event listener: [Link]("event", handler);
● Remove event listener: [Link]("event", handler);
● Dispatch event: [Link](new Event("event"));
● Prevent default behavior: [Link]();
● Stop event propagation: [Link]();
● Stop immediate propagation: [Link]();
● Get event target: let target = [Link];
● Get event current target: let currentTarget = [Link];
● Get event type: let type = [Link];
● Check if event bubbles: let bubbles = [Link];
● Check if event cancelable: let cancelable = [Link];
By: Waleed Mousa
● Get event timestamp: let timestamp = [Link];
● Custom event: let customEvent = new CustomEvent("eventName", {
detail: {} });
● Mouse event coordinates: let x = [Link]; let y =
[Link];
● Keyboard event key: let key = [Link];
● Keyboard event code: let code = [Link];
● Touch event touches: let touches = [Link];
● Drag event dataTransfer: let dataTransfer = [Link];
● Form event submit: [Link]("submit", (e) => {
[Link](); });
● Window load event: [Link]("load", handler);
● Document ready event: [Link]("DOMContentLoaded",
handler);
● Window resize event: [Link]("resize", handler);
● Window scroll event: [Link]("scroll", handler);
● Mutation observer: let observer = new MutationObserver(callback);
● Intersection observer: let observer = new
IntersectionObserver(callback, options);
11. AJAX and Fetch API
● XMLHttpRequest: let xhr = new XMLHttpRequest();
● XMLHttpRequest open: [Link]("GET", url, true);
● XMLHttpRequest send: [Link]();
● XMLHttpRequest onload: [Link] = function() { };
● XMLHttpRequest onerror: [Link] = function() { };
● Fetch API: fetch(url).then(response => [Link]()).then(data =>
[Link](data));
● Fetch with options: fetch(url, { method: "POST", body:
[Link](data) });
● Fetch with headers: fetch(url, { headers: { "Content-Type":
"application/json" } });
● Fetch abort: let controller = new AbortController(); fetch(url, {
signal: [Link] });
● Async/Await with Fetch: let response = await fetch(url); let data =
await [Link]();
● Axios get: [Link](url).then(response =>
[Link]([Link]));
By: Waleed Mousa
● Axios post: [Link](url, data).then(response =>
[Link]([Link]));
● jQuery AJAX: $.ajax({ url: url, method: "GET", success:
function(data) { } });
12. JSON
● Parse JSON: let obj = [Link](jsonString);
● Stringify JSON: let jsonString = [Link](obj);
● Stringify with replacer: [Link](obj, replacer);
● Stringify with space: [Link](obj, null, 2);
● Parse with reviver: [Link](jsonString, reviver);
13. Promises and Async/Await
● Create Promise: let promise = new Promise((resolve, reject) => { });
● Promise then: [Link](result => { });
● Promise catch: [Link](error => { });
● Promise finally: [Link](() => { });
● Promise all: [Link]([promise1, promise2]).then(results => { });
● Promise race: [Link]([promise1, promise2]).then(result => {
});
● Promise allSettled: [Link]([promise1,
promise2]).then(results => { });
● Promise any: [Link]([promise1, promise2]).then(result => { });
● Async function: async function name() { }
● Await: let result = await promise;
● Async/Await with try/catch: try { let result = await promise; } catch
(error) { }
14. Web APIs
● Local Storage set item: [Link]("key", "value");
● Local Storage get item: let value = [Link]("key");
● Local Storage remove item: [Link]("key");
● Local Storage clear: [Link]();
● Session Storage set item: [Link]("key", "value");
● Cookies set: [Link] = "key=value; expires=Thu, 18 Dec 2023
12:00:00 UTC; path=/";
● Cookies get: let value = [Link]('; ').find(row =>
[Link]('key=')).split('=')[1];
By: Waleed Mousa
● Geolocation: [Link](success,
error, options);
● Web Workers: let worker = new Worker('[Link]');
● Service Workers: [Link]('/[Link]');
● Notifications: [Link]().then(permission => {
});
● Push API: [Link](options);
● Fetch API: fetch(url).then(response => [Link]());
● Canvas API: let ctx = [Link]('2d');
● WebGL: let gl = [Link]('webgl');
● WebRTC: let pc = new RTCPeerConnection();
By: Waleed Mousa