06 - JavaScript Cheat Sheet
Learn essential JavaScript cheat sheet with example code, tips, and best practices in simple broken English.
2026-08-29 ยท 7 min read
Hello my friend! Today I show you complete JavaScript Cheat Sheet with code examples and practical tips! This cheat sheet cover all essential syntax you need every day when building web applications! Very easy to read and quick to review. Let's get started!
image by igmguru
1. Variables (const vs let)
Always declare variables using const by default. Only use let when value will change later!
// const: Use for values that will NOT change
const age = 25;
const name = "Rean";
// let: Use for values that WILL change later
let score = 100;
score = 150; // Reassign value!
๐ก Tip: Always use
constby default! Only switch toletwhen you need to reassign value. Never usevarin modern JavaScript!
2. Data Types
JavaScript has 7 primary primitive and reference data types you use every day:
const str = "Hello World"; // String
const num = 42; // Number
const isCool = true; // Boolean
const colors = ["Red", "Green"]; // Array
const user = { name: "Dara" }; // Object
const emptyValue = null; // null (intentional empty value)
let notAssigned; // undefined (variable declared but no value)
๐ก Tip: Use
typeofoperator to check variable data type (e.g.typeof numreturns"number"), but remembertypeof nullreturns"object"!
3. Conditional Statements (if...else)
Control program execution flow based on conditions.
const age = 18;
if (age >= 18) {
console.log("Welcome! You are Adult.");
} else if (age >= 13) {
console.log("You are Teenager.");
} else {
console.log("You are Minor.");
}
๐ก Tip: Always use
===insideifconditions to prevent automatic type conversion bugs!
4. Ternary Operator (Short if...else)
Short 1-line syntax for simple conditional assignment.
const age = 20;
// Short syntax: condition ? valueIfTrue : valueIfFalse
const userStatus = age >= 18 ? "Adult" : "Minor";
console.log(userStatus); // "Adult"
๐ก Tip: Ternary operator is perfect for quick 1-line assignments, but avoid nesting multiple ternaries because it makes code hard to read!
5. Loops (for, for...of, forEach)
Iterate over arrays or repeat code execution easily.
const items = ["Apple", "Banana", "Orange"];
// Standard for loop
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
// for...of loop (cleaner for arrays!)
for (const item of items) {
console.log(item);
}
// forEach method (best for array callback!)
items.forEach((item, index) => {
console.log(`${index + 1}: ${item}`);
});
๐ก Tip: Use
for...ofwhen you want clean loop over array items, andforEach()when you need index and callback function!
6. Functions (Standard vs Arrow Function)
Functions group reusable code logic into callable blocks.
// Standard function declaration
function add(a, b) {
return a + b;
}
// Arrow function (modern & concise!)
const addArrow = (a, b) => a + b;
console.log(add(5, 10)); // 15
console.log(addArrow(5, 10)); // 15
๐ก Tip: Arrow functions do not have their own
thisbinding, making them super helpful inside array methods and DOM callbacks!
7. Useful Array Methods
Transform, filter, and search array items cleanly.
const numbers = [5, 10, 15, 20];
// push: Add item to end
numbers.push(25);
// pop: Remove last item
numbers.pop();
// map: Transform every item into new array
const doubled = numbers.map(x => x * 2); // [10, 20, 30, 40]
// filter: Keep items matching condition
const bigNumbers = numbers.filter(x => x > 10); // [15, 20]
// find: Get 1st matching item
const found = numbers.find(x => x === 15); // 15
// includes: Check if item exists (returns true/false)
const hasTen = numbers.includes(10); // true
๐ก Tip: Methods like
map()andfilter()return brand new array without changing original array!
8. Objects & Property Access
Store data in key-value pairs.
const user = {
name: "Rean",
age: 25,
city: "Phnom Penh"
};
// Dot notation (recommended!)
console.log(user.name); // "Rean"
// Bracket notation (useful for dynamic property keys!)
const key = "city";
console.log(user[key]); // "Phnom Penh"
๐ก Tip: Use bracket notation
user[key]when property name is stored inside variable!
9. Destructuring (Objects & Arrays)
Unpack values from objects or arrays into standalone variables cleanly.
const user = { name: "Rean", age: 25 };
// Object Destructuring
const { name, age } = user;
const colors = ["Red", "Green", "Blue"];
// Array Destructuring
const [firstColor, secondColor] = colors;
๐ก Tip: Destructuring lets you extract object properties or array elements into clean variables in just 1 line of code!
10. Spread Operator (...)
Clone or merge arrays and objects easily.
// Copy & merge arrays
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
// Copy & update object
const user = { name: "Rean", age: 25 };
const updatedUser = { ...user, city: "Phnom Penh" };
๐ก Tip: Spread operator creates shallow copy so you don't modify original object/array by mistake!
11. Template Literals (Backticks)
Embed variables directly inside string using ${}.
const name = "Rean";
const role = "Developer";
// String interpolation with `${}`
const message = `Hello my friend ${name}, you are awesome ${role}!`;
๐ก Tip: Template literals also support multi-line strings without using
\n!
12. DOM Selection & Manipulation
Select HTML elements on page and change text or CSS classes.
// Select single element
const title = document.querySelector("#title");
// Select all elements matching selector
const items = document.querySelectorAll(".item");
// Change text content
title.textContent = "Welcome to JavaScript!";
// Add or remove CSS class
title.classList.add("active");
title.classList.remove("hidden");
๐ก Tip: Use
textContentinstead ofinnerHTMLwhen setting text to avoid XSS security bugs!
13. Event Listeners
Listen to user interactions like clicks, typing, or submits.
const button = document.querySelector("#submitBtn");
button.addEventListener("click", (event) => {
alert("Button clicked my friend!");
});
๐ก Tip: Always attach event listener using
addEventListener()instead of inline HTML attributes (onclick="") to keep HTML and JS separated!
14. Fetch API (HTTP Requests)
Fetch data asynchronously from web server or external API.
// Fetch data from API endpoint
const response = await fetch("https://api.example.com/users");
const data = await response.json();
console.log(data);
๐ก Tip: Remember to call
await response.json()to parse response body into JavaScript object/array!
15. async / await with Error Handling
Handle asynchronous code synchronously and catch runtime errors.
async function getUserData() {
try {
const res = await fetch("/api/users");
const users = await res.json();
return users;
} catch (error) {
console.error("Failed to fetch data:", error);
}
}
๐ก Tip: Always wrap
awaitcalls insidetry...catchblock to handle network failure gracefully without crashing app!
16. Useful JavaScript Operators
Handy operators for comparison, logic, and safe evaluation.
=== // Strict Equality (checks value AND type)
!== // Strict Inequality
&& // Logical AND (both true)
|| // Logical OR (at least one true)
?? // Nullish Coalescing (fallback for null or undefined)
?. // Optional Chaining (safe property access)
๐ก Tip: Combine
?.and??together (e.g.user?.profile?.name ?? "Guest") for bulletproof safe data access!
17. JSON Methods (stringify & parse)
Convert between JavaScript objects and JSON string format.
const user = { name: "Rean", age: 25 };
// Convert object to JSON String
const jsonString = JSON.stringify(user); // '{"name":"Rean","age":25}'
// Parse JSON String back to object
const parsedUser = JSON.parse(jsonString);
๐ก Tip: Use
JSON.stringify()when saving data tolocalStorageor sending payload to web server!
18. Developer Console Methods
Print debug information in browser developer console.
// Standard log output
console.log("Normal log message");
// Display array or object in neat table!
console.table([{ name: "Dara", age: 20 }, { name: "Bopha", age: 22 }]);
// Error log output
console.error("Something went wrong!");
๐ก Tip: Use
console.table()to inspect complex arrays or objects cleanly in browser developer tool console!
Hope this JavaScript Cheat Sheet help you quickly reference all essential syntax easily! Bookmark this page and practice coding every day. Happy learning my friends! Sharing is caring!