JavaScript Cheatsheet
A complete, student-friendly JavaScript cheatsheet. Short, easy explanations and examples for each core concept so you can learn quickly and practise by copying examples.
Variables & Constants
Variables are names (labels) you give to store values. Use let
for values that can change, const
for values that must stay the same, and avoid var
in modern code.
Think of them as boxes: const
locks the box so its name always points to the same value reference.
let count = 1;
const PI = 3.14;
Data Types
JavaScript has primitive types (string, number, boolean, null, undefined, symbol, bigint) and objects (including arrays and functions). Knowing types helps you avoid bugs.
Use typeof
to check simple types, and remember null
is a special value that historically reports as "object".
typeof "hi" // "string"
typeof 10 // "number"
typeof null // "object" (quirk)
Operators
Operators let you do math, compare values, and combine logic. Common ones: +
, -
, ===
(strict equality) and logical operators like &&
and ||
.
Prefer strict equality ===
to avoid unexpected type conversions from ==
.
5 + 3 // 8
5 === "5" // false
true && false // false
Strings
Strings hold text. Use single, double, or backtick quotes. Backticks (template literals) make it easy to insert values into strings using ${...}
.
Helpful methods include slice
, toUpperCase
, and split
.
const name = `Sam`;
`Hello ${"{name}"}` // "Hello Sam"
"name".toUpperCase() // "NAME"
Numbers & Math
Numbers in JS are usually 64-bit floats. Use the Math
object for common functions like Math.round
, Math.max
, and Math.random
.
For precise integer arithmetic beyond Number limits, use BigInt
.
Math.round(4.6) // 5
Math.random() // between 0 and 1
Conditions
Conditions let your code make choices. Use if
/else
or switch
to run different logic based on values.
Keep conditions simple and readable — long nested checks are harder to follow.
if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Loops
Loops repeat actions. Use for
when you know the count, while
to repeat while a condition is true, and for...of
to iterate items.
Use array iteration methods like forEach
, map
and filter
for clearer, functional-style code.
for (let i = 0; i < 3; i++) console.log(i);
const arr = [1,2,3];
arr.map(x => x * 2); // [2,4,6]
Functions
Functions package reusable logic. You can declare named functions or use function expressions and arrow functions for shorter syntax.
Use parameters, default values, and return statements to make functions flexible.
function add(a, b = 0) {
return a + b;
}
const square = x => x * x;
Scope & Hoisting
Scope is where variables are visible: block scope (let/const
) or function/global scope. Hoisting is JS moving some declarations to the top — but only the declarations, not initializations.
Prefer let/const
to avoid surprises from var
's hoisting behavior.
{
let x = 1; // block scoped
}
// console.log(x); // error
Arrays & Useful Methods
Arrays are ordered lists. Use push
, pop
, shift
, unshift
, and higher-order methods like map
, filter
, and reduce
.
Learn map
and filter
— they are incredibly useful and make code concise.
const nums = [1,2,3];
const doubles = nums.map(n => n * 2); // [2,4,6]
const evens = nums.filter(n => n % 2 === 0); // [2]
Objects
Objects hold named values (properties). Use dot or bracket access to read/write properties. Objects can also contain functions (methods).
Use Object.keys
and Object.entries
to loop object properties.
const person = { name: "Sam", age: 20 };
console.log(person.name); // "Sam"
person.city = "Delhi";
Destructuring
Destructuring extracts values from arrays or objects into variables quickly and clearly.
It keeps code shorter and avoids repeated indexing or property access.
const [a, b] = [1, 2];
const {name, age} = {name: "Sam", age: 20};
Spread (...) & Rest (...)
The same three dots do two jobs: spread expands items (e.g., arrays) and rest collects remaining items into an array (e.g., function args).
Use spread to copy/merge arrays or objects, and rest to accept many function arguments.
const arr = [1,2];
const arr2 = [...arr, 3]; // [1,2,3]
function sum(...nums) { return nums.reduce((a,b)=>a+b,0); }
Classes
Classes are a clearer, modern way to create objects with shared behavior. They look like blueprints for objects (instances).
Use class syntax for constructors and methods instead of older prototype-based code.
class Person {
constructor(name) { this.name = name; }
greet() { return "Hi " + this.name; }
}
const p = new Person("Sam");
The this
Keyword
this
refers to the object that is currently using a function. Its value depends on how the function is called.
Arrow functions do not have their own this
; they use this
from the surrounding code.
const obj = {name: "A", getName() { return this.name; }};
Closures
Closures are functions that remember the environment where they were created. That means inner functions can access outer variables even after the outer function runs.
Use closures for private state and factory-style functions.
function makeCounter() {
let n = 0;
return () => ++n;
}
const c = makeCounter(); // c() returns 1, then 2, ...
Callbacks
A callback is a function passed to another function to run later. Callbacks are used for events and async tasks but can lead to nested code if overused.
Modern code often uses Promises and async/await to avoid callback "pyramids".
setTimeout(() => console.log("later"), 1000);
Promises & async/await
Promises represent a future value. Use .then
and .catch
to handle them, or use async/await
for simpler, synchronous-looking code.
Always handle errors from async operations to avoid unhandled rejections.
fetch("/data").then(r => r.json()).then(data => console.log(data));
async function load() { const r = await fetch("/data"); return r.json(); }
Modules (import/export)
Modules let you split code into files. Use export
to share and import
to use code from other files.
This keeps code modular and easier to maintain as projects grow.
// utils.js
export function sum(a,b){return a+b;}
// main.js
import { sum } from "./utils";
JSON (stringify & parse)
JSON is a text format used to exchange data. Use JSON.stringify
to convert an object to JSON and JSON.parse
to turn JSON back into an object.
JSON is common when talking to web APIs or saving simple data.
const obj = {a:1}; const text = JSON.stringify(obj);
const back = JSON.parse(text);
Date & Time
Use the Date
object to work with dates and times. It can be tricky with timezones — for many tasks use libraries or UTC methods.
Basic usage: create a new date and use methods like getFullYear
or toISOString
.
const now = new Date();
now.toISOString();
Error Handling
Use try...catch
to handle errors and keep your program from crashing. You can also throw your own errors with throw
.
Always handle errors in async code too (catch promises or use try/catch in async functions).
try {
JSON.parse("bad");
} catch (e) {
console.error("Invalid JSON");
}
DOM & Events
The DOM (Document Object Model) represents the page structure. Use methods like querySelector
to find elements and addEventListener
to respond to user actions.
Practice selecting elements and changing their textContent
, styles, or classes when events happen.
const btn = document.querySelector("#btn");
btn.addEventListener("click", () => alert("Clicked"));
Events
Events are user actions or browser occurrences (clicks, input, load). Use event listeners to run code when these happen.
Use event.preventDefault()
to stop default browser actions (like form submit) when needed.
form.addEventListener("submit", (e) => { e.preventDefault(); });
Fetch API
Use fetch
to call web APIs. It returns a Promise; convert responses to JSON with response.json()
.
Always handle network errors and bad responses gracefully.
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data));
Local & Session Storage
localStorage
and sessionStorage
let you save small pieces of data in the browser. Local is persistent; session clears when the tab closes.
Store strings; use JSON.stringify/parse for objects.
localStorage.setItem("name","Sam");
const name = localStorage.getItem("name");
Map & Set
Map
stores key-value pairs with any value type as key. Set
stores unique values. They are more flexible than plain objects/arrays for certain tasks.
Use Map when keys are not strings; use Set to remove duplicates.
const s = new Set([1,2,2]); // {1,2}
const m = new Map([["a",1]]);
Optional Chaining (?.)
Optional chaining safely accesses deep properties without throwing errors when a part is undefined. It returns undefined
if something is missing.
Great for handling API responses that may not always include every field.
const name = obj?.person?.name;
Nullish Coalescing (??)
The ??
operator returns the right-hand value only when the left side is null
or undefined
. It’s safer than ||
when you want to allow falsy values like 0.
Use it to provide defaults without overriding valid falsy values.
const port = config.port ?? 8080;
Timers (setTimeout, setInterval)
Use setTimeout
to run code once after a delay, and setInterval
to run code repeatedly. Always clear intervals when you no longer need them.
Timers are useful for UX effects and polling but avoid heavy repeated tasks on short intervals.
const id = setTimeout(() => console.log("hi"), 1000);
const interval = setInterval(() => console.log("tick"), 1000);
clearInterval(interval);
Regular Expressions (RegExp)
Regular expressions are powerful tools to match patterns in strings. They can be complex, so start with simple patterns and test them often.
Use online testers or console experiments to learn how patterns work.
const re = /^d{3}-d{2}-d{4}$/;
re.test("123-45-6789");
Good Practices
Keep functions small, name variables clearly, prefer const
and pure functions where possible, and write small tests or console checks to verify behavior.
Use linters (ESLint) and formatters (Prettier) to keep code consistent and avoid common mistakes.
// small, focused function
function add(a, b) {
return a + b;
}
How to use this page
- Start with basics (variables, types, operators), then practice small examples.
- Move to arrays, objects, functions and ES6 features like destructuring and spread.
- Practice async with Promises and fetch; build small DOM-interactive examples.
- Use the copy buttons to paste examples into your editor or browser console and tweak them.
🚀 Explore More Free Developer Tools
Don’t stop here! Supercharge your workflow with our other powerful converters & formatters.
💡 New tools are added regularly — bookmark DevUtilsX and stay ahead!
Want to support my work?
Buy me a coffee