Introduction
JavaScript is one of the most important programming languages for web development. It helps to make web pages interactive, add dynamic behavior, and work with data on the client side. Whether you want to validate forms, create pop-ups, build complex apps, or just add simple effects to a webpage, JavaScript is the tool to use.
This cheatsheet gives a clear summary of key JavaScript topics. It covers definitions, short code examples, and points you should know.
1. Variables
Definition: Variables store data values.
let name = "John";
const age = 25;
var city = "Delhi";
Point
let
and const
are block-scoped (use them).
- Avoid
var
unless needed for backward compatibility.
2. Data Types
Definition: Types of values that variables can hold.
let num = 10; // Number
let name = "Alice"; // String
let isActive = true; // Boolean
let value = null; // Null
let data; // Undefined
let person = {name: "Bob", age: 30}; // Object
Point: Use typeof
to check data types.
3. Operators
Definition: Symbols to perform actions on variables.
// Arithmetic
let total = 10 + 5;
// Comparison
let isEqual = 5 == '5'; // true
let isStrictEqual = 5 === '5'; // false
// Logical
let check = true && false; // false
Point: Use ===
instead of ==
for strict equality check.
4. Conditional Statements
Definition: Used to make decisions in code.
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor");
}
Point: Use else if
for multiple conditions.
5. Loops
Definition: Used to repeat code.
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Point: Use break
to stop a loop early, and continue
to skip one iteration.
6. Functions
Definition: A block of code that performs a task.
function greet(name) {
return "Hello " + name;
}
console.log(greet("Alice"));
Point: Use functions to reuse code.
7. Arrow Functions
Definition: Shorter syntax for writing functions.
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Point: Arrow functions do not have their own this
.
8. Arrays
Definition: Used to store multiple values.
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[1]); // banana
Point: Use push()
, pop()
, shift()
, unshift()
, slice()
, splice()
for array operations.
9. Objects
Definition: Used to store data in key-value pairs.
let person = {
name: "John",
age: 30
};
console.log(person.name); // John
Point: Use for...in
to loop through object keys.
10. Events
Definition: Used to trigger actions when something happens on the page.
document.getElementById("btn").onclick = function() {
alert("Button clicked");
};
Point: You can also use addEventListener()
for more control.
11. DOM Manipulation
Definition: Used to change the structure or content of HTML using JavaScript.
document.getElementById("title").innerText = "New Title";
Point: Use querySelector()
for more flexible selection.
12. Array Methods
Definition: Built-in methods to work with arrays.
let nums = [1, 2, 3, 4];
// map
let doubled = nums.map(n => n * 2);
// filter
let even = nums.filter(n => n % 2 === 0);
// reduce
let sum = nums.reduce((acc, n) => acc + n, 0);
Point: These methods help in writing clean and short logic.
13. String Methods
Definition: Built-in methods to work with text.
let str = "Hello World";
console.log(str.length); // 11
console.log(str.toUpperCase()); // HELLO WORLD
console.log(str.includes("lo")); // true
Point: Strings are immutable; every change creates a new string.
14. ES6 Features
Template Literals
let name = "John";
console.log(`Hello ${name}`);
Destructuring
let person = { name: "Alice", age: 25 };
let { name, age } = person;
Spread Operator
let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4];
Point: These features make code cleaner and more readable.
15. Try-Catch (Error Handling)
Definition: Used to catch and handle errors.
try {
let result = 10 / 0;
} catch (error) {
console.log("Error occurred:", error.message);
}
Point: Always use this to prevent app crashes.
16. SetTimeout and SetInterval
Definition: Used to run code after a delay or repeatedly.
// Run once after 2 seconds
setTimeout(() => {
console.log("Hi after 2 seconds");
}, 2000);
// Run every 1 second
setInterval(() => {
console.log("Repeating every 1 second");
}, 1000);
Point: Use clearTimeout()
or clearInterval()
to stop them.
17. Promises
Definition: Used to handle asynchronous operations.
let promise = new Promise((resolve, reject) => {
resolve("Success");
});
promise.then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
Point: Useful when working with APIs or delayed data.
18. Async/Await
Definition: Cleaner way to work with promises.
async function getData() {
let result = await fetch("https://api.example.com/data");
let data = await result.json();
console.log(data);
}
Point: Always use await
inside async
functions.
19. this
Keyword
Definition: Refers to the current object in context.
let user = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
user.greet(); // Hello, Alice
Point: In regular functions, this
refers to the object calling the function. In arrow functions, this
refers to the outer scope.
20. call()
, apply()
, and bind()
Definition: Used to control the value of this
.
function greet() {
console.log("Hello, " + this.name);
}
let person = { name: "Bob" };
greet.call(person); // Hello, Bob
Point:
call()
passes arguments one by one
apply()
passes arguments as an array
bind()
returns a new function
21. Closures
Definition: A function that remembers the variables from its outer scope.
function outer() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
let counter = outer();
counter(); // 1
counter(); // 2
Point: Closures help in creating private variables.
22. Hoisting
Definition: JavaScript moves variable and function declarations to the top of the scope.
console.log(x); // undefined
var x = 5;
Point: Only declarations are hoisted, not initializations. let
and const
are hoisted, but in the temporal dead zone until initialized.
23. Truthy and Falsy Values
Definition: JavaScript treats some values as true
or false
in conditions.
if ("") console.log("True"); // will not run
if ("hello") console.log("True"); // will run
Falsy values: false
, 0
, ""
, null
, undefined
, NaN
Point: Use double !!
to convert any value to true or false.
24. Short-Circuit Evaluation
Definition: Logical operators return values based on the first condition.
let name = "" || "Guest";
console.log(name); // Guest
Point: ||
returns the first truthy value, &&
returns the first falsy value.
25. Optional Chaining
Definition: Prevents error when accessing nested properties.
let user = {};
console.log(user.profile?.email); // undefined
Point: Use ?.
to safely access deeply nested properties.
26. Nullish Coalescing
Definition: Returns the right-hand value only if the left is null
or undefined
.
let username = null ?? "Guest";
console.log(username); // Guest
Point: Use ??
instead of ||
when you want to allow falsy values like 0
.
27. Event Delegation
Definition: A technique to handle events on parent instead of individual child elements.
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
console.log("Clicked", e.target.textContent);
}
});
Point: Useful for dynamically added elements and improves performance.
28. Local Storage
Definition: Stores data in the browser that persists after page refresh.
localStorage.setItem("name", "Alice");
console.log(localStorage.getItem("name")); // Alice
Point: Data is saved as strings. Use JSON.stringify()
and JSON.parse()
for objects.
29. Modules (import
/ export
)
Definition: JavaScript modules let you split your code into separate files and reuse logic.
// file: math.js
export function add(a, b) {
return a + b;
}
// file: app.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
Point: Use export
to expose functions/variables. Use import
to bring them into other files. Works in modern browsers or with tools like Webpack.
30. Classes and Inheritance
Definition: Classes let you create objects with shared structure and behavior.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound.");
}
}
class Dog extends Animal {
speak() {
console.log(this.name + " barks.");
}
}
let dog = new Dog("Tommy");
dog.speak(); // Tommy barks.
Point: Use extends
for inheritance and super()
to call the parent constructor.
31. Debouncing
Definition: Delays a function from running until a certain time has passed.
function debounce(fn, delay) {
let timeout;
return function () {
clearTimeout(timeout);
timeout = setTimeout(fn, delay);
};
}
window.addEventListener("resize", debounce(() => {
console.log("Window resized");
}, 500));
Point: Useful for reducing function calls during scroll, input, or resize events.
32. Throttling
Definition: Ensures a function runs at most once in a given time interval.
function throttle(fn, interval) {
let lastTime = 0;
return function () {
let now = Date.now();
if (now - lastTime >= interval) {
fn();
lastTime = now;
}
};
}
window.addEventListener("scroll", throttle(() => {
console.log("Scrolled");
}, 1000));
Point: Useful to limit heavy operations like scrolling or API polling.
33. Custom Events
Definition: Allows you to create and dispatch your own events.
let event = new CustomEvent("hello", {
detail: { name: "Alice" }
});
document.addEventListener("hello", function(e) {
console.log("Hello event received from", e.detail.name);
});
document.dispatchEvent(event);
Point: detail
carries extra data. Good for decoupling parts of your app.
34. Fetch API
Definition: Modern way to make HTTP requests (like calling an API).
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
Point: Use async/await
for better readability with fetch
.
35. JSON (JavaScript Object Notation)
Definition: A format to store and transfer data between client and server.
let user = { name: "Bob", age: 25 };
let str = JSON.stringify(user); // Convert object to string
let obj = JSON.parse(str); // Convert string to object
Point: JSON only supports double quotes and no functions.
36. History API
Definition: Lets you change the browser URL without refreshing the page.
history.pushState({ page: 1 }, "Title", "/page1");
Point: Useful for single-page applications (SPAs) to control navigation.
37. Navigator API
Definition: Gives information about the browser and device.
console.log(navigator.userAgent);
console.log(navigator.onLine);
Point: Useful for detecting device capabilities, online status, geolocation, etc.
38. Clipboard API
Definition: Let's you read from or write to the system clipboard.
navigator.clipboard.writeText("Copied text").then(() => {
console.log("Text copied!");
});
Point: Works only on HTTPS and user interaction (like button click).
39. Event Loop and Call Stack
Definition: JavaScript handles asynchronous tasks using a queue and event loop.
console.log("Start");
setTimeout(() => {
console.log("Timeout");
}, 0);
console.log("End");
Output
Start
End
Timeout
Point: JS is single-threaded. The call stack runs first, then the callback queue via the event loop.
40. Set and Map
- Set: Stores unique values
- Map: Stores key-value pairs
let set = new Set([1, 2, 2, 3]);
console.log(set); // Set(3) {1, 2, 3}
let map = new Map();
map.set("name", "Alice");
console.log(map.get("name")); // Alice
Point
Set
removes duplicates
Map
keys can be objects, unlike regular objects
41. WeakMap and WeakSet
Definition: Like Map
and Set
, but keys must be objects, and they do not prevent garbage collection.
let obj = {};
let weakMap = new WeakMap();
weakMap.set(obj, "value");
Point: Useful for memory-safe private data storage.
42. Generators
Definition: Functions that can pause and resume execution.
function* gen() {
yield 1;
yield 2;
yield 3;
}
let g = gen();
console.log(g.next()); // { value: 1, done: false }
Point: Used in state machines, async flows, and custom iterators.
43. Symbols
Definition: A unique and immutable primitive, used as object keys.
let id = Symbol("id");
let user = { [id]: 123 };
Point: Symbols are not enumerable and prevent property name conflicts.
44. Proxy
Definition: Lets you intercept and customize operations on objects.
let user = { name: "John" };
let proxy = new Proxy(user, {
get(target, prop) {
return prop in target ? target[prop] : "Not found";
}
});
console.log(proxy.age); // Not found
Point: Powerful for validation, logging, and frameworks.
45. Currying
Definition: Transforming a function so it takes one argument at a time.
function add(a) {
return function(b) {
return a + b;
};
}
console.log(add(2)(3)); // 5
Point: Improves reusability and function composition.
46. Memoization
Definition: Caching function results for performance.
function memoize(fn) {
const cache = {};
return function(n) {
if (n in cache) return cache[n];
cache[n] = fn(n);
return cache[n];
};
}
const factorial = memoize(function f(n) {
return n <= 1 ? 1 : n * f(n - 1);
});
Point: Reduces repeated computation in recursive or expensive functions.
47. Functional Programming Concepts
Definition: Writing code using pure functions, immutability, and higher-order functions.
const double = x => x * 2;
const numbers = [1, 2, 3];
const result = numbers.map(double); // [2, 4, 6]
Point: Leads to cleaner, testable, and predictable code.
48. Destructuring and Default Parameters
Destructuring
let { name, age = 18 } = { name: "Tom" };
Default Parameters
function greet(name = "Guest") {
return `Hello ${name}`;
}
Point: Makes code shorter and handles missing values safely.
49. Tagged Template Literals
Definition: Customize how template literals behave.
function tag(strings, value) {
return strings[0] + value.toUpperCase();
}
console.log(tag`Hello ${"world"}`); // Hello WORLD
Point: Used in libraries like styled-components (CSS-in-JS).
50. Object Utility Methods
Object.keys(obj)
– Returns keys
Object.values(obj)
– Returns values
Object.entries(obj)
– Returns key-value pairs
Object.fromEntries()
– Opposite of entries()
Object.assign()
– Merges objects
let obj = { a: 1, b: 2 };
console.log(Object.entries(obj)); // [["a", 1], ["b", 2]]
Conclusion
You now have a complete, end-to-end JavaScript cheatsheet covering:
- Basics (variables, loops, functions)
- Intermediate (DOM, arrays, objects, async)
- Advanced (closures, event loop, modules, proxies)
- Modern ES6+ features
- Real-world tools (fetch, storage, debouncing)
- Best practices (functional programming, memoization)