JavaScript Cheat Sheet: Basics

Variables

Declaring Variables
  • var (function-scoped, avoid in modern code)
  • let (block-scoped, recommended)
  • const (block-scoped, constant)

Example:

let name = "Alice";
const age = 25;
var city = "Berlin";
Variable Naming Rules
  • Case-sensitive
  • Cannot start with a number
  • Use letters, $, _

Data Types

Primitive Types
  • String
  • Number
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt
Reference Types
  • Objects
  • Arrays
  • Functions

Example:

let name = "Bob";            // String
let score = 95;              // Number
let isActive = true;         // Boolean
let data = null;             // Null
let car;                     // Undefined
let user = { name: "Sam" };  // Object
let list = [1, 2, 3];        // Array

Operators

Arithmetic

+, -, *, /, %, **

Assignment

=, +=, -=, *=, /=

Comparison

==, ===, !=, !==, <, >, <=, >=

Logical

&&, ||, !

Increment / Decrement

++, --


Control Structures

If Statements
if (score > 90) {
  console.log("Great!");
} else if (score > 75) {
  console.log("Good!");
} else {
  console.log("Keep trying!");
}
Switch Statements
let color = "green";
switch (color) {
  case "red":
    console.log("Stop");
    break;
  case "green":
    console.log("Go");
    break;
  default:
    console.log("Unknown color");
}
Loops

For Loop:

for (let i = 0; i < 5; i++) {
  console.log(i);
}

While Loop:

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

Functions

Declaring Functions
function greet(name) {
  return `Hello, ${name}`;
}
Arrow Functions
const greet = (name) => `Hello, ${name}`;
Function Expressions
const add = function(a, b) {
  return a + b;
};

Objects

Creating Objects
const person = {
  name: "Jane",
  age: 30,
  greet: function() {
    console.log("Hello!");
  }
};
Accessing Properties
console.log(person.name);
person.greet();

Arrays

Creating Arrays
const fruits = ["apple", "banana", "orange"];
Accessing Elements
console.log(fruits[0]); // "apple"
Array Methods
  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • slice()
  • forEach()
  • map()
  • filter()