Coding Cheatsheets

Quick reference guides for programming essentials. Bookmark this page!

📦 Variables

// Declaring variables
let name = "Alice";       // Can be changed
const PI = 3.14159;       // Cannot be changed
var oldWay = "avoid";     // Old syntax, avoid using

// Updating variables
name = "Bob";             // OK
PI = 3;                   // Error! const cannot change

// Variable naming rules
let camelCase = "good";   // Start lowercase, capitalize words
let _private = "ok";      // Can start with underscore
let $money = 100;         // Can start with $
// let 1stPlace = "";     // Cannot start with number

🏷️ Data Types

// Primitive Types
let str = "Hello";        // String
let num = 42;             // Number
let decimal = 3.14;       // Number (no separate float)
let bool = true;          // Boolean (true/false)
let nothing = null;       // Null (intentionally empty)
let notDefined;           // Undefined

// Reference Types
let arr = [1, 2, 3];      // Array
let obj = {name: "Alice"};  // Object

// Check type
typeof "hello"            // "string"
typeof 42                 // "number"
typeof true               // "boolean"
typeof undefined          // "undefined"
typeof null               // "object" (JS quirk!)
typeof [1,2]              // "object"
typeof {}                 // "object"

🔢 Operators

// Arithmetic
5 + 3    // 8  (addition)
5 - 3    // 2  (subtraction)
5 * 3    // 15 (multiplication)
5 / 3    // 1.6666666666666667 (division — never truncated)
5 % 3    // 2  (remainder/modulo)
5 ** 3   // 125 (exponent)

// JavaScript has no separate integer division.
// For a whole-number result, floor it yourself:
Math.floor(5 / 3)   // 1
Math.trunc(-5 / 3)  // -1 (floor would give -2)

// Comparison (returns true/false)
5 === 5     // true  (strict equal — same value AND same type)
5 == "5"    // true  (loose equal converts the string first)
5 === "5"   // false (different types)
5 !== 3     // true  (strict not equal)
5 > 3       // true
5 < 3       // false
5 >= 5      // true
5 <= 3      // false

// Prefer === and !==. Loose == has surprising rules:
0 == ""         // true
null == undefined  // true
NaN == NaN      // false (nothing equals NaN)

// Logical
true && true   // true (AND)
true || false  // true (OR)
!true          // false (NOT)

// Assignment shortcuts
x += 5   // x = x + 5
x -= 3   // x = x - 3
x *= 2   // x = x * 2
x++      // x = x + 1
x--      // x = x - 1

🔀 Conditionals

// If statement
if (condition) {
  // runs if true
}

// If-else
if (condition) {
  // runs if true
} else {
  // runs if false
}

// If-else if-else
if (score >= 90) {
  grade = "A";
} else if (score >= 80) {
  grade = "B";
} else {
  grade = "C";
}

// Ternary operator (shorthand)
let result = condition ? "yes" : "no";

// Switch
switch (day) {
  case "Mon":
    console.log("Monday");
    break;
  case "Tue":
    console.log("Tuesday");
    break;
  default:
    console.log("Other day");
}

🔄 Loops

// For loop
for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

// While loop
let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

// For...of (iterate values)
let fruits = ["apple", "banana"];
for (let fruit of fruits) {
  console.log(fruit);
}

// For...in (iterate keys/indices)
for (let index in fruits) {
  console.log(index);  // 0, 1
}

// forEach (array method)
fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});

// Loop control (only valid inside a loop —
// a bare break/continue is a SyntaxError)
for (let i = 0; i < 10; i++) {
  if (i === 2) continue;  // Skip to next iteration
  if (i === 5) break;     // Exit loop entirely
  console.log(i);         // 0, 1, 3, 4
}

Functions

// Four ways to write the same function.
// Each needs its own name: one program cannot
// declare "greet" more than once.

// 1. Function declaration
function greetA(name) {
  return "Hello, " + name;
}

// 2. Function expression
const greetB = function(name) {
  return "Hello, " + name;
};

// 3. Arrow function
const greetC = (name) => {
  return "Hello, " + name;
};

// 4. Arrow function (short form — implicit return)
const greetD = name => "Hello, " + name;

// Default parameters
function greetOrStranger(name = "World") {
  return "Hello, " + name;
}

// Rest parameters
function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}

// Calling functions
greetA("Alice");           // "Hello, Alice"
greetOrStranger();         // "Hello, World"
sum(1, 2, 3, 4);           // 10

📋 Arrays

// Create array (use the literal — it is shorter
// and avoids the new Array(3) length trap)
let arr = [1, 2, 3];
// new Array(1, 2, 3) → [1, 2, 3]
// new Array(3)       → 3 empty slots, NOT [3]

// Access elements (0-indexed)
arr[0]           // 1 (first)
arr[arr.length-1] // 3 (last)

// Modify
arr[0] = 10;     // Change element
arr.push(4);     // Add to end
arr.pop();       // Remove from end
arr.unshift(0);  // Add to start
arr.shift();     // Remove from start

// Common methods
arr.length       // Number of elements
arr.indexOf(2)   // Find index (or -1)
arr.includes(2)  // Check if exists
arr.slice(1, 3)  // Get portion (new array)
arr.splice(1,1)  // Remove elements (modifies)
arr.concat([4,5]) // Combine arrays
arr.join(", ")   // Array to string

// Transform
arr.map(x => x * 2)        // Transform each
arr.filter(x => x > 2)     // Keep matching
arr.reduce((a,b) => a+b)   // Combine all
arr.find(x => x > 2)       // First match
arr.sort()                 // Sort (alphabetically)
arr.reverse()              // Reverse order

🧊 Objects

// Create object
let person = {
  name: "Alice",
  age: 30,
  greet: function() {
    return "Hi, I'm " + this.name;
  }
};

// Access properties
person.name          // Dot notation
person["name"]       // Bracket notation
person.greet()       // Call method

// Check properties
"name" in person     // true
person.hasOwnProperty("name") // true

// Get keys/values
Object.keys(person)   // ["name", "age", "greet"]
Object.values(person) // ["Alice", 30, function]
Object.entries(person) // [["name","Alice"],...]

// Modify
person.age = 31;     // Update (age is now 31)
person.city = "NYC"; // Add new
delete person.city;  // Remove

// Loop through
for (let key in person) {
  console.log(key, person[key]);
}

// Destructuring
const { name, age } = person;

// Spread operator
const copy = { ...person };
const merged = { ...person, city: "NYC" };