JavaScript is the undisputed backbone of modern web development. Whether you are building interactive frontend user interfaces, writing backend logic with Node.js, or preparing for a technical interview, having a quick-reference guide can save you hours of documentation-diving.
This comprehensive JavaScript cheat sheet covers everything from fundamental variables to advanced asynchronous patterns using modern ES6+ syntax. Bookmark this page so you can return to it whenever you hit a roadblock.
1. Variables and Core Data Types
In modern JavaScript (ES6 and later), the old var keyword is obsolete due to its unpredictable scoping behaviors. Instead, we use const and let, which are both strictly block-scoped.
const: Declares a variable whose reference cannot be reassigned. Use this by default.let: Declares a variable that can be reassigned later.
// Variable Declarations
const pi = 3.14159; // Cannot be reassigned
let counter = 0; // Can be modified later: counter = 1;
// Primitive Data Types
const username = "Alice"; // String
const age = 30; // Number (handles integers and floats)
const isDeveloper = true; // Boolean
const modernFeatures = null; // Null (an intentional absence of value)
let futureValue; // Undefined (declared but not given a value)
const uniqueKey = Symbol(); // Symbol (guaranteed unique identifier)
const bigNumber = 900719925n; // BigInt (for numbers larger than Number.MAX_SAFE_INTEGER)
2. Working with Strings and Template Literals
Gone are the days of clunky string concatenation using the + operator. Modern JavaScript uses backticks (“) for template literals, allowing clean variable interpolation and effortless multi-line strings.
const user = "Sam";
// String Interpolation
const greeting = `Hello, ${user}! Welcome to our platform.`;
// Essential String Methods
console.length; // Returns length
greeting.toUpperCase(); // Converts to uppercase ("HELLO, SAM!...")
greeting.includes("Sam"); // Checks for substring (returns true)
greeting.slice(0, 5); // Extracts a section (returns "Hello")
3. Conditionals and Strict Comparisons
To write bug-free code, always use strict equality (===) instead of loose equality (==). Strict equality compares both the value and the data type, avoiding JavaScript’s unpredictable automatic type coercion.
// Comparisons
5 === "5"; // false (different types: Number vs String)
5 == "5"; // true (loose equality forces types to match - avoid this!)
// Logical Operators
// && (AND) -> both must be true
// || (OR) -> at least one must be true
// ! (NOT) -> inverts a boolean
// Ternary Operator (The short-hand 'if-else')
// Syntax: condition ? expression_if_true : expression_if_false;
const status = age >= 18 ? "Adult" : "Minor";
4. Modern Functions and Arrow Syntax
Functions are the primary building blocks of JavaScript applications. While traditional function declarations are still widely used, arrow functions (=>) provide a cleaner, shorter syntax and bind the this context lexically.
// 1. Traditional Function Declaration (Hoisted)
function greet(name) {
return `Hello ${name}`;
}
// 2. Modern Arrow Function
const greetArrow = (name) => `Hello ${name}`;
// 3. Default Parameters (Prevents 'undefined' bugs)
const welcome = (name = "Guest") => `Welcome, ${name}`;
5. Array Methods (The Functional Way)
Arrays are zero-indexed lists used to store sequences of elements. Instead of relying on manual for loops, leverage built-in JavaScript high-order array methods to transform and filter data natively.
const fruits = ["Apple", "Banana", "Orange"];
// Mutating Methods (Modifies the original array)
fruits.push("Mango"); // Adds element to the end
fruits.pop(); // Removes the last element
fruits.unshift("Kiwi"); // Adds element to the front
fruits.shift(); // Removes the first element
// Functional Iterators (Returns a new array/value without mutating original)
const lengths = fruits.map(fruit => fruit.length); // Transforms: [5, 6, 6]
const longFruits = fruits.filter(fruit => fruit.length > 5); // Filters: ["Banana", "Orange"]
const foundFruit = fruits.find(fruit => fruit === "Apple"); // Finds first match: "Apple"
6. Objects: Storing Key-Value Pairs
Objects allow you to group related data and functionality together into a single structured entity.
const person = {
firstName: "Jane",
lastName: "Doe",
age: 25,
greet: function() {
return `Hi, I'm ${this.firstName}`;
}
};
// Accessing Object Properties
console.log(person.firstName); // Dot notation (Preferred)
console.log(person["lastName"]); // Bracket notation (Useful for dynamic keys)
// Dynamically adding properties
person.job = "Developer";
7. ES6+ Destructuring and the Spread Operator
Destructuring and the spread operator (...) make extracting and cloning data from objects and arrays incredibly expressive and neat.
// Object Destructuring
const { firstName, age } = person; // Extracts person.firstName and person.age into direct variables
// Array Destructuring
const [firstFruit, secondFruit] = fruits; // assigns firstFruit = "Apple", secondFruit = "Banana"
// The Spread Operator (...) for Cloning and Merging
const originalArray = [1, 2, 3];
const clonedArray = [...originalArray]; // Creates a shallow copy
const mergedArray = [...originalArray, 4, 5]; // [1, 2, 3, 4, 5]
// Merging and updating objects
const updatedPerson = { ...person, age: 26 }; // Copies person, but overwrites age to 26
8. DOM Manipulation: Interacting with the Browser
When running JavaScript in a web browser, the Document Object Model (DOM) is your bridge to the HTML user interface. This is how you change text, handle click events, and toggle styles.
// Selecting HTML Elements
const headline = document.getElementById("main-title");
const submitBtn = document.querySelector(".btn-submit"); // Selects by CSS class/tag
const listItems = document.querySelectorAll(".item"); // Returns an array-like NodeList
// Modifying Content and Styles
headline.textContent = "Welcome to the Dashboard";
headline.style.color = "#2ef2a0";
headline.classList.add("is-visible"); // Adds a CSS class
// Handling Events
submitBtn.addEventListener("click", (event) => {
event.preventDefault(); // Prevents page reload if inside a form
console.log("Button clicked! Target:", event.target);
});
9. Asynchronous JavaScript: Promises & Async/Await
JavaScript operates on a single thread, meaning it can only do one thing at a time. To prevent your app from freezing during time-consuming operations (like fetching data from an API), JavaScript handles tasks asynchronously using Promises or Async/Await.
Traditional Promise Syntax
const fetchData = () => {
return new Promise((resolve, reject) => {
let success = true;
if (success) resolve("Data successfully retrieved!");
else reject("Data fetch failed.");
});
};
fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));
Modern Async/Await (Cleaner, Readability of Synchronous Code)
async function getWebData() {
try {
const response = await fetch("https://api.example.com/users");
if (!response.ok) throw new Error("Network response was not ok");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch operation failed:", error);
}
}
Wrap Up
Keep this JavaScript cheat sheet handy as you build your next project. JavaScript is a vast language that is continually evolving, but mastering these core fundamentals—variables, arrays, objects, DOM manipulation, and asynchronous patterns—will give you the foundation to tackle any framework, be it React, Vue, or Next.js.
