JavaScript Cheat Sheet

Use this JavaScript cheat sheet as a quick reference for variables, data types, operators, functions, arrays, objects, loops, DOM methods, events, promises, async code, and common patterns.

Basic JavaScript Syntax

JavaScript statements usually run from top to bottom.

JavaScript

const message = "Hello, JavaScript";
console.log(message);

Syntax Basics

  • Use const for values that should not be reassigned.
  • Use let for values that need to change.
  • End statements with semicolons for consistency.
  • Use comments to explain why code exists, not every obvious line.
  • Use console.log() to inspect values while debugging.

Add JavaScript to HTML

External JavaScript File

<script src="script.js"></script>

Place it near the end of the <body> when the script needs to access page elements.

<body>
    <button id="button">Click me</button>
    <script src="script.js"></script>
</body>

Inline JavaScript

<script>
    console.log("Page loaded");
</script>

External files are better for most projects because they keep HTML and JavaScript separate.

Comments

Single-Line Comment

JavaScript

// This is a single-line comment

Multi-Line Comment

JavaScript

/*
This comment can span
multiple lines.
*/

Variables

const

Use const when the variable should not be reassigned.

JavaScript

const username = "Alex";
console.log(username);

let

Use let when the value needs to change.

JavaScript

let count = 0;
count = count + 1;
console.log(count);

Avoid var in Modern JavaScript

JavaScript

var oldStyle = "Avoid this in new code";

var has function scope and can cause confusing behavior. Use const and let instead.

Data Types

String

JavaScript

const name = "Alex";

Number

JavaScript

const price = 19.99;
const quantity = 3;

Boolean

JavaScript

const isLoggedIn = true;
const hasAccess = false;

Null

Use null when a value is intentionally empty.

JavaScript

const selectedUser = null;

Undefined

undefined often means a value has not been assigned.

JavaScript

let result;
console.log(result);

Object

JavaScript

const user = {
    name: "Alex",
    age: 28
};

Array

JavaScript

const languages = ["HTML", "CSS", "JavaScript"];

Check a Type

Use typeof for basic type checks.

JavaScript

console.log(typeof "Hello");
console.log(typeof 42);
console.log(typeof true);

Check arrays with Array.isArray().

JavaScript

const items = ["a", "b", "c"];

console.log(Array.isArray(items));

Strings

Create a String

JavaScript

const greeting = "Hello";

Template Literal

JavaScript

const name = "Alex";
const message = `Hello, ${name}`;

String Length

JavaScript

const text = "JavaScript";
console.log(text.length);

Change Case

JavaScript

const text = "JavaScript";

console.log(text.toLowerCase());
console.log(text.toUpperCase());

Check If a String Includes Text

JavaScript

const title = "Learn JavaScript";

console.log(title.includes("JavaScript"));

Trim Whitespace

JavaScript

const input = "  hello  ";
console.log(input.trim());

Split a String

JavaScript

const tags = "html,css,javascript";
const list = tags.split(",");

console.log(list);

Numbers

Basic Math

JavaScript

const total = 10 + 5;
const difference = 10 - 5;
const product = 10 * 5;
const quotient = 10 / 5;

Remainder

JavaScript

const remainder = 10 % 3;
console.log(remainder);

Round Numbers

JavaScript

console.log(Math.round(4.6));
console.log(Math.floor(4.9));
console.log(Math.ceil(4.1));

Generate a Random Number

JavaScript

const random = Math.random();
console.log(random);

Random Integer Between 1 and 10

JavaScript

const randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(randomNumber);

Operators

Assignment

JavaScript

let score = 10;
score += 5;
score -= 2;
score *= 3;
score /= 2;

Comparison

JavaScript

console.log(10 > 5);
console.log(10 >= 10);
console.log(5 < 10);
console.log(5 <= 5);

Equality

JavaScript

console.log(5 === 5);
console.log(5 !== "5");

Use === and !== instead of == and != in most code.

Logical Operators

JavaScript

const isAdult = true;
const hasTicket = false;

console.log(isAdult && hasTicket);
console.log(isAdult || hasTicket);
console.log(!isAdult);

Conditionals

if

JavaScript

const age = 20;

if (age >= 18) {
    console.log("Adult");
}

if...else

JavaScript

const isLoggedIn = false;

if (isLoggedIn) {
    console.log("Welcome back");
} else {
    console.log("Please log in");
}

else if

JavaScript

const score = 85;

if (score >= 90) {
    console.log("A");
} else if (score >= 80) {
    console.log("B");
} else {
    console.log("Keep practicing");
}

Ternary Operator

JavaScript

const age = 20;
const message = age >= 18 ? "Adult" : "Minor";

console.log(message);

Use ternaries for short decisions. Use if...else when the logic needs multiple lines.

switch

JavaScript

const role = "admin";

switch (role) {
    case "admin":
        console.log("Full access");
        break;
    case "editor":
        console.log("Edit access");
        break;
    default:
        console.log("Read access");
}

Functions

Function Declaration

JavaScript

function greet(name) {
    return `Hello, ${name}`;
}

console.log(greet("Alex"));

Function Expression

JavaScript

const greet = function(name) {
    return `Hello, ${name}`;
};

Arrow Function

JavaScript

const greet = (name) => {
    return `Hello, ${name}`;
};

Short Arrow Function

JavaScript

const double = (number) => number * 2;

console.log(double(5));

Default Parameter

JavaScript

function greet(name = "Guest") {
    return `Hello, ${name}`;
}

console.log(greet());

Arrays

Create an Array

JavaScript

const fruits = ["apple", "banana", "orange"];

Access Items

JavaScript

const fruits = ["apple", "banana", "orange"];

console.log(fruits[0]);
console.log(fruits[1]);

Array Length

JavaScript

console.log(fruits.length);

Add Items

JavaScript

const fruits = ["apple", "banana"];

fruits.push("orange");
fruits.unshift("mango");

console.log(fruits);

Remove Items

JavaScript

const fruits = ["apple", "banana", "orange"];

fruits.pop();
fruits.shift();

console.log(fruits);

Find an Item

JavaScript

const users = ["Alex", "Sam", "Taylor"];

const user = users.find((name) => name === "Sam");
console.log(user);

Check If an Array Includes a Value

JavaScript

const languages = ["HTML", "CSS", "JavaScript"];

console.log(languages.includes("CSS"));

Loop with forEach

JavaScript

const fruits = ["apple", "banana", "orange"];

fruits.forEach((fruit) => {
    console.log(fruit);
});

Create a New Array with map

JavaScript

const numbers = [1, 2, 3];

const doubled = numbers.map((number) => number * 2);

console.log(doubled);

Filter an Array

JavaScript

const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter((number) => number % 2 === 0);

console.log(evenNumbers);

Reduce an Array

JavaScript

const prices = [10, 20, 30];

const total = prices.reduce((sum, price) => sum + price, 0);

console.log(total);

Objects

Create an Object

JavaScript

const user = {
    name: "Alex",
    age: 28,
    isMember: true
};

Access Properties

JavaScript

console.log(user.name);
console.log(user["age"]);

Update Properties

JavaScript

user.age = 29;
user.city = "Vienna";

console.log(user);

Destructure an Object

JavaScript

const user = {
    name: "Alex",
    age: 28
};

const { name, age } = user;

console.log(name);
console.log(age);

Object Methods

JavaScript

const user = {
    name: "Alex",
    greet() {
        return `Hello, ${this.name}`;
    }
};

console.log(user.greet());

Get Object Keys and Values

JavaScript

const user = {
    name: "Alex",
    age: 28
};

console.log(Object.keys(user));
console.log(Object.values(user));
console.log(Object.entries(user));

Loops

for Loop

JavaScript

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

for...of

Use for...of to loop over arrays, strings, and other iterable values.

JavaScript

const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
    console.log(fruit);
}

for...in

Use for...in to loop over object keys.

JavaScript

const user = {
    name: "Alex",
    age: 28
};

for (const key in user) {
    console.log(key, user[key]);
}

while

JavaScript

let count = 0;

while (count < 3) {
    console.log(count);
    count++;
}

Scope

Block Scope

let and const are block-scoped.

JavaScript

if (true) {
    const message = "Inside block";
    console.log(message);
}

The variable only exists inside the block.

Function Scope

Variables created inside a function stay inside that function.

JavaScript

function showMessage() {
    const message = "Hello";
    console.log(message);
}

showMessage();

DOM Selection

Select One Element

JavaScript

const title = document.querySelector("h1");

Select by Class

JavaScript

const card = document.querySelector(".card");

Select by ID

JavaScript

const button = document.querySelector("#submit-button");

Select Multiple Elements

JavaScript

const items = document.querySelectorAll(".item");

Loop through selected elements:

JavaScript

items.forEach((item) => {
    console.log(item.textContent);
});

Change Page Content

Change Text

JavaScript

const title = document.querySelector("h1");

title.textContent = "New title";

Change HTML

JavaScript

const container = document.querySelector(".container");

container.innerHTML = "<p>New content</p>";

Use textContent for plain text. Use innerHTML only when you trust the HTML content.

Change Attributes

JavaScript

const link = document.querySelector("a");

link.setAttribute("href", "https://example.com");

Change Styles

JavaScript

const box = document.querySelector(".box");

box.style.backgroundColor = "blue";
box.style.color = "white";

For larger style changes, add or remove classes instead.

Classes

Add a Class

JavaScript

const box = document.querySelector(".box");

box.classList.add("active");

Remove a Class

JavaScript

box.classList.remove("active");

Toggle a Class

JavaScript

box.classList.toggle("active");

Check for a Class

JavaScript

console.log(box.classList.contains("active"));

Events

Click Event

JavaScript

const button = document.querySelector("button");

button.addEventListener("click", () => {
    console.log("Button clicked");
});

Input Event

JavaScript

const input = document.querySelector("#search");

input.addEventListener("input", (event) => {
    console.log(event.target.value);
});

Submit Event

JavaScript

const form = document.querySelector("form");

form.addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("Form submitted");
});

Keyboard Event

JavaScript

document.addEventListener("keydown", (event) => {
    console.log(event.key);
});

Create and Remove Elements

Create an Element

JavaScript

const paragraph = document.createElement("p");
paragraph.textContent = "New paragraph";

Add It to the Page

JavaScript

document.body.appendChild(paragraph);

Remove an Element

JavaScript

const alert = document.querySelector(".alert");

alert.remove();

JSON

Convert Object to JSON

JavaScript

const user = {
    name: "Alex",
    age: 28
};

const json = JSON.stringify(user);

console.log(json);

Convert JSON to Object

JavaScript

const json = '{"name":"Alex","age":28}';

const user = JSON.parse(json);

console.log(user.name);

Error Handling

try...catch

JavaScript

try {
    const user = JSON.parse('{"name":"Alex"}');
    console.log(user.name);
} catch (error) {
    console.log("Something went wrong");
}

Throw an Error

JavaScript

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }

    return a / b;
}

Promises

Basic Promise

JavaScript

const promise = new Promise((resolve) => {
    resolve("Done");
});

promise.then((result) => {
    console.log(result);
});

Fetch Data

JavaScript

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log("Request failed", error);
    });

Async and Await

Use async and await to write promise-based code in a cleaner style.

JavaScript

async function getPost() {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();

    console.log(data);
}

getPost();

Async Error Handling

JavaScript

async function getPost() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");

        if (!response.ok) {
            throw new Error("Request failed");
        }

        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.log(error.message);
    }
}

getPost();

Modules

Export a Function

JavaScript

export function add(a, b) {
    return a + b;
}

Import a Function

JavaScript

import { add } from "./math.js";

console.log(add(2, 3));

Default Export

JavaScript

export default function greet(name) {
    return `Hello, ${name}`;
}

Default Import

JavaScript

import greet from "./greet.js";

console.log(greet("Alex"));

Timers

setTimeout

Runs code once after a delay.

JavaScript

setTimeout(() => {
    console.log("Runs after 1 second");
}, 1000);

setInterval

Runs code repeatedly.

JavaScript

const intervalId = setInterval(() => {
    console.log("Runs every second");
}, 1000);

Stop an interval:

JavaScript

clearInterval(intervalId);

Local Storage

Save Data

JavaScript

localStorage.setItem("theme", "dark");

Read Data

JavaScript

const theme = localStorage.getItem("theme");

console.log(theme);

Remove Data

JavaScript

localStorage.removeItem("theme");

Store an Object

JavaScript

const user = {
    name: "Alex",
    role: "developer"
};

localStorage.setItem("user", JSON.stringify(user));

Read the object:

JavaScript

const savedUser = JSON.parse(localStorage.getItem("user"));

console.log(savedUser.name);

Common JavaScript Patterns

Toggle a Menu

JavaScript

const menuButton = document.querySelector(".menu-button");
const menu = document.querySelector(".menu");

menuButton.addEventListener("click", () => {
    menu.classList.toggle("is-open");
});

Form Validation

JavaScript

const form = document.querySelector("form");
const email = document.querySelector("#email");

form.addEventListener("submit", (event) => {
    if (!email.value.includes("@")) {
        event.preventDefault();
        console.log("Enter a valid email address");
    }
});

Filter a List

JavaScript

const products = [
    { name: "HTML Course", category: "web" },
    { name: "Python Course", category: "programming" },
    { name: "CSS Course", category: "web" }
];

const webCourses = products.filter((product) => product.category === "web");

console.log(webCourses);

Find a User by ID

JavaScript

const users = [
    { id: 1, name: "Alex" },
    { id: 2, name: "Sam" }
];

const user = users.find((user) => user.id === 2);

console.log(user);

Count Items

JavaScript

const cart = [
    { title: "Course", price: 20 },
    { title: "Book", price: 15 }
];

const total = cart.reduce((sum, item) => sum + item.price, 0);

console.log(total);

Common Mistakes

Using = Instead of ===

JavaScript

if (isLoggedIn = true) {
    console.log("Welcome");
}

Better:

JavaScript

if (isLoggedIn === true) {
    console.log("Welcome");
}

Forgetting const or let

JavaScript

name = "Alex";

Better:

JavaScript

const name = "Alex";

Changing a const Variable

JavaScript

const count = 1;
count = 2;

Better:

JavaScript

let count = 1;
count = 2;

Use let when reassignment is needed.

Using innerHTML with Unsafe Data

JavaScript

element.innerHTML = userInput;

Better:

JavaScript

element.textContent = userInput;

Use textContent for plain user-provided text.

Forgetting event.preventDefault() on Forms

JavaScript

form.addEventListener("submit", () => {
    console.log("Submitted");
});

Better:

JavaScript

form.addEventListener("submit", (event) => {
    event.preventDefault();
    console.log("Submitted");
});

Use this when you want to handle the form with JavaScript instead of letting the browser submit it normally.

Debugging Tips

Log Values

JavaScript

console.log(user);

Log Labels

JavaScript

console.log("Current user:", user);

Check Errors in the Browser Console

Open DevTools and use the Console tab to see errors, warnings, and log messages.

Use debugger

JavaScript

function calculateTotal(items) {
    debugger;
    return items.reduce((sum, item) => sum + item.price, 0);
}

When DevTools is open, debugger pauses the code at that line.

Check If an Element Exists

JavaScript

const button = document.querySelector(".button");

if (button) {
    button.addEventListener("click", () => {
        console.log("Clicked");
    });
}

This prevents errors when the element is missing.

Quick Reference

Declare a Variable

JavaScript

const name = "Alex";
let count = 0;

Create a Function

JavaScript

function greet(name) {
    return `Hello, ${name}`;
}

Create an Arrow Function

JavaScript

const greet = (name) => `Hello, ${name}`;

Create an Array

JavaScript

const items = ["one", "two", "three"];

Create an Object

JavaScript

const user = {
    name: "Alex",
    age: 28
};

Select an Element

JavaScript

const button = document.querySelector("button");

Add an Event Listener

JavaScript

button.addEventListener("click", () => {
    console.log("Clicked");
});

Fetch Data

JavaScript

const response = await fetch("https://example.com/api");
const data = await response.json();

Handle Errors

JavaScript

try {
    // code
} catch (error) {
    console.log(error.message);
}