dev.rean.me
javascript

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

Share:

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!

JavaScript Cheat Sheet by igmguru 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 const by default! Only switch to let when you need to reassign value. Never use var in 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 typeof operator to check variable data type (e.g. typeof num returns "number"), but remember typeof null returns "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 === inside if conditions 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...of when you want clean loop over array items, and forEach() 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 this binding, 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() and filter() 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 textContent instead of innerHTML when 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 await calls inside try...catch block 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 to localStorage or 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!