Skip to content

JavaScript Cheat Sheet

This lesson explains JavaScript Cheat Sheet in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.

JavaScript Cheatsheet Overview

This JavaScript cheatsheet is a quick reference guide for beginners, frontend developers, full-stack developers, and interview preparation. It covers JavaScript syntax, reserved keywords, data types, operators, arrays, strings, objects, functions, loops, DOM methods, storage, timers, promises, async/await, and common built-in methods.

Use this cheatsheet to quickly revise important JavaScript concepts, syntax patterns, and frequently used methods while building real-world web applications.

JavaScript Quick Syntax Example

const user = {
  name: "John",
  role: "Developer",
  active: true
};

function greetUser(userInfo) {
  if (userInfo.active === true) {
    return "Hello " + userInfo.name;
  }

  return "User is inactive";
}

const message = greetUser(user);

console.log(message);

This example shows object syntax, function syntax, conditional logic, strict equality, return values, and console output.

JavaScript Reserved Keywords

Category Reserved Words
Control Flow if, else, switch, case, default, break, continue, return, throw, try, catch, finally
Loops for, while, do, in, of
Declarations var, let, const, function, class, extends, import, export, default
Object and Class this, super, new, static, constructor, get, set
Async async, await, yield
Values and Types true, false, null, undefined, NaN, Infinity
Operators and Checks typeof, instanceof, void, delete
Strict Mode Reserved implements, interface, package, private, protected, public
Future Reserved enum

JavaScript Data Types Cheatsheet

Data Type Description Example
StringText value.const name = "John";
NumberInteger or decimal number.const price = 99.99;
BigIntLarge integer value.const big = 12345678901234567890n;
BooleanTrue or false value.const active = true;
UndefinedDeclared but not assigned.let value;
NullIntentional empty value.const result = null;
SymbolUnique identifier.const id = Symbol("id");
ObjectKey-value collection.const user = { name: "John" };
ArrayOrdered list.const items = ["A", "B"];
FunctionReusable block of code.function add(a, b) { return a + b; }

JavaScript Operators Complete List

Operator Type Operators Example
Arithmetic+, -, *, /, %, **, ++, --const total = a + b;
Assignment=, +=, -=, *=, /=, %=, **=count += 1;
Comparison==, ===, !=, !==, >, <, >=, <=age === 18
Logical&&, ||, !active && verified
Nullish??, ??=const limit = value ?? 10;
Optional Chaining?.user.address?.city
Conditional? :const status = active ? "Yes" : "No";
Typetypeof, instanceoftypeof name
Spread and Rest...const copy = [...items];
Bitwise&, |, ^, ~, <<, >>, >>>a & b

JavaScript Array Methods Cheatsheet

Method Purpose Syntax
push()Adds item at end.items.push("A");
pop()Removes last item.items.pop();
shift()Removes first item.items.shift();
unshift()Adds item at start.items.unshift("A");
map()Transforms values.items.map(item => item.name);
filter()Filters values.items.filter(item => item.active);
find()Finds first match.items.find(item => item.id === 1);
findIndex()Finds first matching index.items.findIndex(item => item.id === 1);
reduce()Returns accumulated value.prices.reduce((sum, price) => sum + price, 0);
forEach()Runs function for each item.items.forEach(item => console.log(item));
some()Checks if any item matches.items.some(item => item.active);
every()Checks if all items match.items.every(item => item.active);
includes()Checks value exists.items.includes("A");
indexOf()Returns first index.items.indexOf("A");
slice()Returns selected copy.items.slice(1, 3);
splice()Adds or removes items.items.splice(1, 1);
sort()Sorts array.numbers.sort((a, b) => a - b);
reverse()Reverses array.items.reverse();
join()Converts array to string.items.join(", ");
flat()Flattens nested array.items.flat();
flatMap()Maps and flattens.items.flatMap(item => item.tags);
at()Gets item by index.items.at(-1);
toSorted()Returns sorted copy.numbers.toSorted((a, b) => a - b);
toReversed()Returns reversed copy.items.toReversed();
toSpliced()Returns spliced copy.items.toSpliced(1, 1);
with()Returns copy with updated item.items.with(0, "New");

JavaScript String Methods Cheatsheet

Method Purpose Syntax
lengthReturns string length.name.length
charAt()Returns character at index.text.charAt(0)
at()Returns character by index.text.at(-1)
includes()Checks substring exists.text.includes("JS")
startsWith()Checks starting text.text.startsWith("Hello")
endsWith()Checks ending text.text.endsWith(".js")
indexOf()Returns first index.text.indexOf("a")
lastIndexOf()Returns last index.text.lastIndexOf("a")
slice()Extracts part of string.text.slice(0, 5)
substring()Extracts characters.text.substring(0, 5)
split()Converts string to array.text.split(",")
replace()Replaces first match.text.replace("old", "new")
replaceAll()Replaces all matches.text.replaceAll("old", "new")
trim()Removes whitespace.text.trim()
trimStart()Removes start whitespace.text.trimStart()
trimEnd()Removes end whitespace.text.trimEnd()
toUpperCase()Converts to uppercase.text.toUpperCase()
toLowerCase()Converts to lowercase.text.toLowerCase()
padStart()Pads from start.id.padStart(5, "0")
padEnd()Pads from end.id.padEnd(5, "0")
repeat()Repeats string."-".repeat(10)
match()Matches regex pattern.text.match(/[0-9]+/)
search()Searches regex pattern.text.search(/JS/)

JavaScript Object Methods Cheatsheet

Method / Feature Purpose Example
Object.keys()Returns object keys.Object.keys(user)
Object.values()Returns object values.Object.values(user)
Object.entries()Returns key/value pairs.Object.entries(user)
Object.assign()Copies properties.Object.assign({}, user)
Object.freeze()Makes object immutable.Object.freeze(config)
Object.seal()Prevents adding/removing properties.Object.seal(settings)
hasOwnProperty()Checks direct property.user.hasOwnProperty("name")
deleteRemoves a property.delete user.age
inChecks property existence."name" in user
spreadCopies or merges objects.{ ...user, active: true }

JavaScript Functions Cheatsheet

Function Type Syntax Use Case
Function Declarationfunction add(a, b) { return a + b; }Reusable named function.
Function Expressionconst add = function(a, b) { return a + b; };Assign function to variable.
Arrow Functionconst add = (a, b) => a + b;Short function syntax.
Default Parameterfunction greet(name = "Guest") { ... }Fallback value.
Rest Parameterfunction sum(...numbers) { ... }Collect many arguments.
Callbackitems.forEach(item => console.log(item));Pass function as argument.
Immediately Invoked Function(function() { ... })();Run once immediately.
Higher-Order Functionfunction fn(cb) { return cb(); }Works with other functions.

JavaScript Number and Math Cheatsheet

Method / Constant Purpose Example
Number()Converts to number.Number("42")
parseInt()Parses integer.parseInt("42px")
parseFloat()Parses decimal.parseFloat("42.5")
isNaN()Checks Not-a-Number.isNaN(value)
Number.isNaN()Strict NaN check.Number.isNaN(value)
Math.round()Rounds to nearest integer.Math.round(4.6)
Math.floor()Rounds down.Math.floor(4.9)
Math.ceil()Rounds up.Math.ceil(4.1)
Math.max()Returns highest value.Math.max(1, 5, 9)
Math.min()Returns lowest value.Math.min(1, 5, 9)
Math.random()Returns random number.Math.random()
Math.abs()Returns absolute value.Math.abs(-12)

JavaScript Date and JSON Cheatsheet

API Purpose Example
new Date()Creates current date.const now = new Date();
getFullYear()Gets year.date.getFullYear()
getMonth()Gets month index.date.getMonth()
toISOString()Returns ISO string.date.toISOString()
JSON.stringify()Converts object to JSON.JSON.stringify(user)
JSON.parse()Converts JSON to object.JSON.parse(jsonText)
toLocaleDateString()Formats readable date.date.toLocaleDateString()
toLocaleTimeString()Formats readable time.date.toLocaleTimeString()

JavaScript DOM and Events Cheatsheet

Method / Feature Purpose Example
querySelector()Selects first matching element.document.querySelector("#title")
querySelectorAll()Selects all matching elements.document.querySelectorAll(".item")
getElementById()Selects element by id.document.getElementById("title")
addEventListener()Adds event listener.button.addEventListener("click", fn)
classList.add()Adds CSS class.el.classList.add("active")
classList.remove()Removes CSS class.el.classList.remove("active")
textContentSets or gets text.el.textContent = "Hello"
innerHTMLSets HTML content.el.innerHTML = "<b>Hi</b>"
preventDefault()Stops default action.event.preventDefault()
stopPropagation()Stops event bubbling.event.stopPropagation()

JavaScript Quick Reference

Concept Syntax
Variableconst name = "John";
Functionfunction add(a, b) { return a + b; }
Arrow Functionconst add = (a, b) => a + b;
Objectconst user = { name: "John" };
Arrayconst items = ["A", "B"];
If Elseif (active) { run(); } else { stop(); }
For Loopfor (let i = 0; i < 5; i++) { console.log(i); }
For Offor (const item of items) { console.log(item); }
Try Catchtry { run(); } catch (error) { console.log(error.message); }
Promisepromise.then(result => console.log(result));
Async Awaitconst data = await fetchData();
Fetchconst response = await fetch("/api/users");
DOM Selectdocument.querySelector("#title")
Eventbutton.addEventListener("click", handleClick);
Local StoragelocalStorage.setItem("theme", "dark");

Key Takeaways

  • This JavaScript cheatsheet gives a quick reference for common syntax and methods.
  • Reserved keywords cannot be used as normal variable names.
  • JavaScript has primitive and non-primitive data types.
  • Operators are used for arithmetic, comparison, assignment, logic, and type checks.
  • Array and string methods are essential for real-world data manipulation.
  • Use this cheatsheet for revision, interviews, and daily JavaScript development.

Pro Tip

Bookmark this JavaScript cheatsheet and revise it regularly. The fastest way to improve JavaScript skills is to understand syntax patterns, practice small examples, and apply them in real projects.