Getting Started
5 snippetsYour 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 booleanCheck Type
typeof variable // "string", "number"
Array.isArray(arr) // true/falseVariables & Data Types
8 snippetsDeclaring 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 snippetsSymbols 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 // trueLogical
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 methodBitwise
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.
Loops
10 snippetsRepeating 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 snippetsMaking 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 snippetsFunction
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 snippetsMap
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 snippetsPromise
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 snippetsQuery
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 snippetsExport
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 snippetsES6 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); // 5Getters/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 snippetsBuilt-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; // 0Map 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); // trueGenerators
4 snippetsPausable 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; // 1Iterate 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 snippetsSymbol, 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; // TypeErrorProxy
const handler = {
get(target, prop) {
return prop in target ? target[prop] : "default";
}
};
const proxy = new Proxy({}, handler);
proxy.anything; // "default"