AI Generate JavaScript docs instantly

JavaScript Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Getting Started

5 snippets

Your first steps with JavaScript basics

Hello World

console.log("Hello, World!");

Comments

// Single line comment
/* Multi-line
   comment */

User Input

const name = prompt("Enter your name:");

Type Conversion

Number("42")   // str to number
String(42)     // number to str
Boolean(1)     // to boolean

Check Type

typeof variable  // "string", "number"
Array.isArray(arr)  // true/false

Variables & Data Types

8 snippets

Declaring and using different data types

Let

let name = "John";

Const

const PI = 3.14159;

Array

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

Object

const person = { name: "John", age: 30 };

Template Literal

const greeting = `Hello, ${name}!`;

Destructuring

const { name, age } = person;

Spread

const newArr = [...arr1, ...arr2];

Null/Undefined

let empty = null;
let notDefined = undefined;

Operators

7 snippets

Symbols for calculations and comparisons

Arithmetic

5 + 3   // 8 (addition)
5 - 3   // 2 (subtraction)
5 * 3   // 15 (multiplication)
5 / 3   // 1.666... (division)
5 % 3   // 2 (modulus)
5 ** 3  // 125 (exponent)
let x = 5; x++  // 6 (increment)

Comparison

5 == "5"   // true (loose, coerces types)
5 === "5"  // false (strict, no coercion)
5 != "5"   // false
5 !== "5"  // true
5 > 3      // true
5 <= 5     // true

Logical

true && false   // false (AND)
true || false   // true (OR)
!true           // false (NOT)
null ?? "default"  // "default" (nullish)

Assignment

let x = 5   // Assign
x += 3      // x = 8 (add)
x -= 2      // x = 6 (subtract)
x *= 2      // x = 12 (multiply)
x /= 3      // x = 4 (divide)
x ??= 10    // x = 4 (nullish assign)

Ternary

const age = 20;
const status = age >= 18 ? "adult" : "minor";
// status = "adult"

Optional Chaining

const user = { profile: { name: "John" } };
user?.profile?.name    // "John"
user?.address?.city    // undefined (no error)
user?.getName?.()      // undefined if no method

Bitwise

5 & 3   // 1 (AND: 101 & 011)
5 | 3   // 7 (OR: 101 | 011)
5 ^ 3   // 6 (XOR)
~5      // -6 (NOT)
5 << 1  // 10 (left shift)
5 >> 1  // 2 (right shift)

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Loops

10 snippets

Repeating code blocks efficiently

For

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

For...of (Arrays)

for (const item of array) {
    console.log(item);
}

For...in (Objects)

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

ForEach

array.forEach((item, index) => {
    console.log(index, item);
});

While

while (count < 10) {
    count++;
}

Do While

do {
    count++;
} while (count < 10);

Break

for (let i = 0; i < 10; i++) {
    if (i === 5) break;
}

Continue

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

For with entries

for (const [i, val] of arr.entries()) {
    console.log(i, val);
}

Map keys/values

for (const [key, val] of map) {
    console.log(key, val);
}

Conditionals

5 snippets

Making decisions in your code

If/Else

if (x > 0) {
    console.log("positive");
} else if (x < 0) {
    console.log("negative");
} else {
    console.log("zero");
}

Ternary

const result = condition ? "yes" : "no";

Switch

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

Nullish Check

const name = user ?? "Guest";
const len = str?.length ?? 0;

Short-circuit

isValid && doSomething();
isEmpty || setDefault();

Functions

4 snippets

Function

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

Arrow Function

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

Default Params

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

Rest Params

function sum(...nums) {
    return nums.reduce((a, b) => a + b, 0);
}

Array Methods

6 snippets

Map

const doubled = nums.map(n => n * 2);

Filter

const evens = nums.filter(n => n % 2 === 0);

Reduce

const sum = nums.reduce((a, b) => a + b, 0);

Find

const found = users.find(u => u.id === 1);

Some/Every

const hasNeg = nums.some(n => n < 0);

Sort

nums.sort((a, b) => a - b);

Async/Promises

4 snippets

Promise

const promise = new Promise((resolve, reject) => {
    resolve("success");
});

Async/Await

async function fetchData() {
    const res = await fetch(url);
    return await res.json();
}

Try/Catch Async

try {
    const data = await fetchData();
} catch (error) {
    console.error(error);
}

Promise.all

const results = await Promise.all([p1, p2, p3]);

DOM Manipulation

5 snippets

Query

const el = document.querySelector(".class");

Query All

const els = document.querySelectorAll("div");

Event

el.addEventListener("click", (e) => {});

Create

const div = document.createElement("div");

Append

parent.appendChild(child);

Modules

4 snippets

Export

export const name = "John";

Export Default

export default function greet() {}

Import

import { name } from "./module.js";

Import Default

import greet from "./module.js";

Classes

5 snippets

ES6 class syntax

Basic Class

class Person {
    constructor(name) {
        this.name = name;
    }

    greet() {
        return `Hello, ${this.name}!`;
    }
}

Inheritance

class Employee extends Person {
    constructor(name, role) {
        super(name);
        this.role = role;
    }

    describe() {
        return `${this.name} is a ${this.role}`;
    }
}

Static Methods

class MathUtils {
    static add(a, b) {
        return a + b;
    }

    static PI = 3.14159;
}

MathUtils.add(2, 3);  // 5

Getters/Setters

class Circle {
    constructor(radius) {
        this._radius = radius;
    }

    get radius() {
        return this._radius;
    }

    set radius(value) {
        this._radius = Math.max(0, value);
    }

    get area() {
        return Math.PI * this._radius ** 2;
    }
}

Private Fields

class Counter {
    #count = 0;  // Private field

    increment() {
        this.#count++;
    }

    get value() {
        return this.#count;
    }
}

Map & Set

5 snippets

Built-in collection types

Map

const map = new Map();
map.set("key", "value");
map.get("key");     // "value"
map.has("key");     // true
map.delete("key");
map.size;           // 0

Map from Array

const map = new Map([
    ["a", 1],
    ["b", 2]
]);

// Iterate
for (const [key, val] of map) {
    console.log(key, val);
}

Set

const set = new Set([1, 2, 2, 3]);
set.add(4);
set.has(2);       // true
set.delete(2);
set.size;         // 3

// Unique array
[...new Set([1, 1, 2, 2, 3])]  // [1, 2, 3]

WeakMap

// Keys must be objects, garbage collected
const cache = new WeakMap();
const obj = {};
cache.set(obj, "data");
cache.get(obj);  // "data"

WeakSet

// Values must be objects, garbage collected
const seen = new WeakSet();
const obj = {};
seen.add(obj);
seen.has(obj);  // true

Generators

4 snippets

Pausable functions with yield

Basic Generator

function* countUp() {
    yield 1;
    yield 2;
    yield 3;
}

const gen = countUp();
gen.next();  // { value: 1, done: false }
gen.next();  // { value: 2, done: false }

Infinite Generator

function* infiniteSequence() {
    let i = 0;
    while (true) {
        yield i++;
    }
}

const gen = infiniteSequence();
gen.next().value;  // 0
gen.next().value;  // 1

Iterate Generator

function* range(start, end) {
    for (let i = start; i <= end; i++) {
        yield i;
    }
}

for (const num of range(1, 5)) {
    console.log(num);  // 1, 2, 3, 4, 5
}

yield*

function* concat(a, b) {
    yield* a;
    yield* b;
}

const result = [...concat([1, 2], [3, 4])];
// [1, 2, 3, 4]

Advanced Types

4 snippets

Symbol, BigInt, and more

Symbol

const id = Symbol("id");
const obj = {
    [id]: 123,
    name: "test"
};

obj[id];  // 123
Object.keys(obj);  // ["name"] (symbol hidden)

Well-known Symbols

// Make object iterable
const obj = {
    *[Symbol.iterator]() {
        yield 1;
        yield 2;
    }
};

[...obj];  // [1, 2]

BigInt

const big = 9007199254740991n;
const alsoBig = BigInt("9007199254740991");

big + 1n;    // 9007199254740992n
big * 2n;    // 18014398509481982n

// Cannot mix with regular numbers
// big + 1;  // TypeError

Proxy

const handler = {
    get(target, prop) {
        return prop in target ? target[prop] : "default";
    }
};

const proxy = new Proxy({}, handler);
proxy.anything;  // "default"

More Cheat Sheets

FAQ

Frequently asked questions

What is a JavaScript cheat sheet?

A JavaScript cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in JavaScript. It helps developers quickly look up syntax without searching through documentation.

How do I learn JavaScript quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important JavaScript concepts?

Key JavaScript concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my JavaScript code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your JavaScript code using AI.

Code Conversion Tools

Convert JavaScript to Other Languages

Easily translate your JavaScript code to other programming languages with our AI-powered converters

Related resources

Stop memorizing. Start shipping.

Generate JavaScript Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week