console.log('Hello, world!');Print to the console.
A massive searchable, copy-ready JavaScript reference covering core syntax, arrays, objects, classes, promises, async/await, DOM, events, browser APIs, Node.js, npm, testing, regex, modules, and more.
console.log('Hello, world!');Print to the console.
let age = 18;Declare a block-scoped variable.
const name = 'Ada';Declare a block-scoped constant.
var legacy = true;Declare a function-scoped variable; generally prefer let/const.
let nothing = null;Represent an intentional empty value.
let missing;Declare a variable whose value is undefined.
typeof valueReturn a string describing a value's type.
Number('42')Convert text to a number.
String(123)Convert a value to text.
Boolean(value)Convert a value to true/false.
parseInt('42', 10)Parse an integer.
parseFloat('3.14')Parse a floating-point number.
Number.isNaN(value)Check specifically for NaN.
const x = 1, y = 2;Declare multiple variables.
[a, b] = [b, a];Swap two variables using destructuring.
// commentSingle-line comment.
/* multi-line comment */Block comment.
7 + 3Addition.
7 - 3Subtraction.
7 * 3Multiplication.
7 / 3Division.
7 % 3Remainder.
2 ** 8Exponentiation.
x += 1Add using compound assignment.
x *= 2Multiply using compound assignment.
a === bStrict equality.
a !== bStrict inequality.
a == bLoose equality with type coercion; usually avoid.
a > bGreater than.
a >= bGreater than or equal.
a && bLogical AND.
a || bLogical OR.
!aLogical NOT.
a ?? bNullish coalescing.
condition ? yes : noTernary conditional.
Math.abs(-8)Absolute value.
Math.round(3.6)Round to nearest integer.
Math.floor(3.9)Round down.
Math.ceil(3.1)Round up.
Math.max(...nums)Maximum value.
Math.min(...nums)Minimum value.
Math.random()Pseudo-random number from 0 inclusive to 1 exclusive.
const text = 'hello';Create a string.
const text = "hello";Create a string with double quotes.
const text = `hello`;Create a template literal.
text.lengthGet string length.
text[0]Get first character.
text.at(-1)Get last character.
text.slice(1, 4)Extract part of a string.
text.substring(1, 4)Extract substring.
text.toUpperCase()Convert to uppercase.
text.toLowerCase()Convert to lowercase.
text.trim()Remove leading/trailing whitespace.
text.trimStart()Remove leading whitespace.
text.trimEnd()Remove trailing whitespace.
text.includes('cat')Check substring presence.
text.startsWith('pre')Check prefix.
text.endsWith('.txt')Check suffix.
text.indexOf('cat')Find substring index.
text.replace('old', 'new')Replace first match.
text.replaceAll('old', 'new')Replace all literal matches.
text.split(',')Split into an array.
items.join(', ')Join array items into a string.
`Hello ${name}`Interpolate values with a template literal.
`${price.toFixed(2)}`Format a number inside a template literal.
const items = [1, 2, 3];Create an array.
items[0]Get first item.
items.at(-1)Get last item.
items.lengthGet array length.
items.push(4)Append an item.
items.pop()Remove and return the last item.
items.unshift(0)Add an item to the beginning.
items.shift()Remove and return the first item.
items.slice(1, 3)Copy a section of an array.
items.splice(1, 1)Remove/replace items in place.
items.includes('x')Check membership.
items.indexOf('x')Find first matching index.
items.find(x => x.id === 1)Find first matching element.
items.findIndex(x => x.id === 1)Find first matching index.
items.sort()Sort in place lexicographically.
items.sort((a, b) => a - b)Sort numbers ascending.
items.reverse()Reverse in place.
[...items].sort()Sort a shallow copy.
items.concat(other)Concatenate arrays.
[...items, ...other]Concatenate with spread syntax.
Array.from(iterable)Create an array from an iterable.
Array.isArray(value)Check whether a value is an array.
items.map(x => x * 2)Transform each item.
items.filter(x => x > 0)Keep matching items.
items.reduce((sum, x) => sum + x, 0)Reduce to one value.
items.forEach(x => console.log(x))Run a function for each item.
items.some(x => x > 10)Check whether any item matches.
items.every(x => x > 0)Check whether all items match.
items.flat()Flatten one array level.
items.flat(2)Flatten two levels.
items.flatMap(x => [x, x * 2])Map and flatten one level.
items.entries()Get index/value iterator.
items.keys()Get index iterator.
items.values()Get value iterator.
const user = { name: 'Ada', age: 18 };Create an object.
user.nameRead a property with dot syntax.
user['name']Read a property with bracket syntax.
user.email = '[email protected]';Add or update a property.
delete user.age;Delete a property.
'name' in userCheck property existence.
Object.keys(user)Get own enumerable keys.
Object.values(user)Get own enumerable values.
Object.entries(user)Get key/value pairs.
Object.assign({}, user)Shallow-copy properties.
const copy = { ...user };Shallow-copy with spread syntax.
const merged = { ...a, ...b };Merge objects; later properties win.
Object.freeze(user)Prevent top-level changes.
Object.seal(user)Prevent adding/removing properties.
Object.hasOwn(user, 'name')Check own property.
const [a, b] = items;Array destructuring.
const [first, ...rest] = items;Capture remaining array items.
const { name, age } = user;Object destructuring.
const { name: fullName } = user;Rename while destructuring.
const { role = 'user' } = user;Provide a default value.
const copy = [...items];Shallow-copy an array.
const copy = { ...user };Shallow-copy an object.
func(...items)Spread array items into function arguments.
if (x > 0) { console.log('positive'); }Basic if statement.
if (x > 0) { } else { }if/else.
if (x > 0) { } else if (x === 0) { } else { }if/else-if/else.
const status = age >= 18 ? 'adult' : 'minor';Ternary expression.
switch (value) { case 'a': break; default: break; }Switch statement.
if (value == null) { }Match null or undefined with loose null check.
if (!items.length) { }Check for an empty array.
for (let i = 0; i < 10; i++) { }Classic for loop.
for (const item of items) { }Loop over iterable values.
for (const key in object) { }Loop over enumerable object keys.
while (condition) { }Repeat while condition is true.
do { } while (condition);Run at least once.
break;Exit the nearest loop or switch.
continue;Skip to the next loop iteration.
for (const [i, item] of items.entries()) { }Loop with indexes.
function greet(name) { return `Hello ${name}`; }Function declaration.
const greet = function(name) { return `Hello ${name}`; };Function expression.
const greet = name => `Hello ${name}`;Arrow function.
const add = (a, b = 0) => a + b;Arrow function with default parameter.
function sum(...nums) { return nums.reduce((a,b) => a+b, 0); }Rest parameter.
return value;Return a value.
function outer() { function inner() { } }Nested function.
(() => console.log('run'))();Immediately invoked function expression.
let x = 1;Block-scoped variable.
const x = 1;Block-scoped constant.
var x = 1;Function-scoped variable.
function makeCounter() { let n = 0; return () => ++n; }Closure retaining private state.
globalThisReference the global object across environments.
class User { }Define a class.
const u = new User();Create an instance.
class User { constructor(name) { this.name = name; } }Define a constructor.
u.nameAccess instance property.
class User { greet() { return this.name; } }Define an instance method.
class Admin extends User { }Create a subclass.
super(name);Call parent constructor.
super.greet();Call parent method.
static create() { return new User(); }Define a static method.
get fullName() { return this.name; }Define a getter.
set fullName(v) { this.name = v; }Define a setter.
#secret = 123;Define a private class field.
instanceof UserCheck prototype-based instance relationship.
Object.getPrototypeOf(obj)Get an object's prototype.
Object.create(proto)Create an object with a specified prototype.
User.prototype.greet = function() { }Add a method to a constructor's prototype.
obj.hasOwnProperty('x')Legacy own-property check.
try { risky(); } catch (err) { console.error(err); }Catch an exception.
try { } catch (err) { } finally { cleanup(); }Always run cleanup.
throw new Error('Something failed');Throw a generic error.
throw new TypeError('Expected a string');Throw a type-related error.
err.messageRead error message.
err.stackRead stack trace when available.
class AppError extends Error { }Create a custom error type.
const p = Promise.resolve(42);Create an already-resolved promise.
const p = Promise.reject(new Error('fail'));Create an already-rejected promise.
promise.then(value => console.log(value))Handle fulfillment.
promise.catch(err => console.error(err))Handle rejection.
promise.finally(() => cleanup())Run code after settle.
Promise.all([p1, p2])Wait for all promises; rejects on first rejection.
Promise.allSettled([p1, p2])Wait for all promises regardless of result.
Promise.race([p1, p2])Settle with the first settled promise.
Promise.any([p1, p2])Fulfill with the first successful promise.
async function main() { }Define an async function.
const value = await promise;Wait for a promise inside async context.
await fetch('/api/data');Await a network request.
try { await task(); } catch (err) { }Handle async errors.
const [a, b] = await Promise.all([taskA(), taskB()]);Run async tasks concurrently.
const res = await fetch('/api/data');Send a GET request.
const data = await res.json();Parse JSON response.
const text = await res.text();Read response as text.
res.okCheck 2xx response status.
res.statusRead HTTP status code.
await fetch('/api/items', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify(data) });POST JSON data.
await fetch(url, { method: 'DELETE' });Send a DELETE request.
const controller = new AbortController();Create an abort controller.
fetch(url, { signal: controller.signal });Attach abort signal.
controller.abort();Cancel an in-flight fetch.
JSON.stringify(obj)Convert a value to JSON text.
JSON.stringify(obj, null, 2)Pretty-print JSON.
JSON.parse(text)Parse JSON text.
JSON.parse(text, reviver)Parse JSON with a reviver.
JSON.stringify(obj, replacer)Customize serialization.
new Date()Create a Date for the current time.
new Date('2026-09-18T12:00:00Z')Parse an ISO-style timestamp.
Date.now()Current epoch time in milliseconds.
date.getFullYear()Get local year.
date.getMonth()Get local zero-based month.
date.getDate()Get local day of month.
date.toISOString()Format as ISO 8601 UTC.
date.toLocaleString()Format using local conventions.
new Intl.DateTimeFormat('en-US').format(date)Format with Intl.
new Intl.RelativeTimeFormat('en').format(-1, 'day')Format relative time.
const re = /\d+/;Create a regex literal.
new RegExp('\\d+')Create a regex dynamically.
re.test(text)Test whether regex matches.
text.match(/\d+/g)Return regex matches.
text.matchAll(/(\w+)/g)Iterate over matches and groups.
text.replace(/\s+/g, ' ')Regex replacement.
text.split(/[,;]/)Regex split.
re.exec(text)Execute regex and return match data.
const set = new Set([1, 2, 2]);Create a set with unique values.
set.add(3)Add a value.
set.has(2)Check membership.
set.delete(2)Delete a value.
set.sizeGet set size.
const map = new Map();Create a Map.
map.set('name', 'Ada')Set a key/value pair.
map.get('name')Read a value.
map.has('name')Check for a key.
map.delete('name')Delete a key.
map.sizeGet map size.
Object.fromEntries(map)Convert Map entries into a plain object.
items[Symbol.iterator]()Get an iterator.
iterator.next()Get the next iterator result.
function* numbers() { yield 1; yield 2; }Define a generator.
yield value;Yield one value from a generator.
yield* iterable;Delegate to another iterable.
for (const x of numbers()) { }Iterate over generator output.
export const value = 42;Export a named value.
export default function main() { }Export a default value.
import { value } from './module.js';Import a named export.
import main from './module.js';Import a default export.
import * as utils from './utils.js';Import all named exports as an object.
const module = await import('./module.js');Dynamically import a module.
document.getElementById('app')Select an element by ID.
document.querySelector('.card')Select the first matching element.
document.querySelectorAll('.card')Select all matching elements.
element.closest('.panel')Find nearest matching ancestor.
element.matches('.active')Check whether an element matches a selector.
element.parentElementGet parent element.
element.childrenGet child elements.
element.firstElementChildGet first child element.
document.createElement('div')Create an element.
element.textContent = 'Hello';Set text safely.
element.innerHTML = '<b>Hello</b>';Set HTML markup; avoid with untrusted content.
element.append(child)Append nodes or text.
element.prepend(child)Prepend nodes or text.
element.remove()Remove an element.
element.replaceWith(newElement)Replace an element.
element.setAttribute('title', 'Info')Set an attribute.
element.getAttribute('title')Read an attribute.
element.removeAttribute('title')Remove an attribute.
element.classList.add('active')Add a class.
element.classList.remove('active')Remove a class.
element.classList.toggle('active')Toggle a class.
element.style.display = 'none';Set an inline style.
button.addEventListener('click', handler);Listen for click events.
element.removeEventListener('click', handler);Remove an event listener.
event.preventDefault();Prevent default browser behavior.
event.stopPropagation();Stop event bubbling.
event.targetElement that originally triggered the event.
event.currentTargetElement whose handler is currently running.
document.addEventListener('DOMContentLoaded', () => { });Run when the DOM is ready.
form.addEventListener('submit', event => { event.preventDefault(); });Handle form submission.
input.addEventListener('input', event => console.log(event.target.value));React to text input.
input.valueRead an input's value.
checkbox.checkedRead checkbox state.
select.valueRead selected option value.
new FormData(form)Collect form fields.
Object.fromEntries(new FormData(form))Convert form fields to a plain object.
form.reset()Reset form controls.
input.setCustomValidity('Invalid value')Set custom validation message.
form.checkValidity()Check HTML form validity.
localStorage.setItem('theme', 'dark')Store persistent string data.
localStorage.getItem('theme')Read persistent data.
localStorage.removeItem('theme')Remove one item.
localStorage.clear()Clear all local storage for the origin.
sessionStorage.setItem('token', 'x')Store session-only string data.
sessionStorage.getItem('token')Read session data.
JSON.parse(localStorage.getItem('settings') || '{}')Load JSON-like settings.
localStorage.setItem('settings', JSON.stringify(settings))Store structured data as JSON.
setTimeout(() => console.log('later'), 1000)Run once after a delay.
clearTimeout(id)Cancel a timeout.
setInterval(() => tick(), 1000)Run repeatedly.
clearInterval(id)Cancel an interval.
queueMicrotask(() => task())Queue a microtask.
requestAnimationFrame(() => draw())Schedule browser animation work.
navigator.userAgentRead browser user-agent string.
navigator.clipboard.writeText('hello')Copy text to clipboard with permission.
location.hrefCurrent page URL.
location.reload()Reload the page.
history.back()Go back in browser history.
history.pushState({}, '', '/new-path')Add a history entry without full navigation.
new URL('https://example.com/path?x=1')Create a URL object.
new URLSearchParams(location.search)Parse query parameters.
console.log(process.version)Show Node.js version.
console.log(process.argv)Read command-line arguments.
process.env.NODE_ENVRead an environment variable.
process.cwd()Get current working directory.
process.chdir('/tmp')Change working directory.
process.exit(0)Exit the process.
__dirnameCurrent module directory in CommonJS.
__filenameCurrent file path in CommonJS.
const fs = require('fs');Import fs in CommonJS.
import fs from 'node:fs';Import fs in ESM.
fs.readFileSync('file.txt', 'utf8')Read a file synchronously.
fs.writeFileSync('file.txt', 'hello')Write a file synchronously.
await fs.promises.readFile('file.txt', 'utf8')Read a file asynchronously.
await fs.promises.writeFile('file.txt', 'hello')Write a file asynchronously.
await fs.promises.mkdir('dir', { recursive: true })Create nested directories.
await fs.promises.readdir('.')List directory contents.
await fs.promises.rm('dir', { recursive: true, force: true })Delete a directory tree. ⚠
const path = require('path');Import path in CommonJS.
path.join('a', 'b', 'file.txt')Join path segments.
path.resolve('file.txt')Resolve an absolute path.
path.basename('/tmp/file.txt')Get final path component.
path.dirname('/tmp/file.txt')Get parent directory.
path.extname('file.txt')Get file extension.
import.meta.urlCurrent module URL in ESM.
import http from 'node:http';Import Node HTTP module.
http.createServer((req, res) => { res.end('Hello'); }).listen(3000);Create a basic HTTP server.
req.methodRead HTTP method.
req.urlRead request URL.
res.statusCode = 200;Set response status.
res.setHeader('Content-Type', 'application/json');Set response header.
res.end(JSON.stringify({ok:true}));Send response body.
npm init -yCreate a package.json with defaults.
npm install packageInstall a dependency.
npm install -D packageInstall a development dependency.
npm uninstall packageRemove a dependency.
npm updateUpdate dependencies within allowed version ranges.
npm outdatedShow outdated dependencies.
npm listShow installed dependency tree.
npm run scriptRun a package.json script.
npm testRun the test script.
npm auditCheck dependencies for known vulnerabilities.
npm audit fixApply compatible security fixes.
npm ciInstall exactly from package-lock.json for reproducible builds.
"type": "module"Treat .js files as ES modules in Node.
"scripts": { "start": "node app.js" }Define an npm start script.
"dependencies": { }Runtime dependencies.
"devDependencies": { }Development-only dependencies.
"engines": { "node": ">=20" }Document expected Node version.
console.assert(x === 1, 'x should equal 1');Simple built-in assertion.
import assert from 'node:assert/strict';Import Node strict assertions.
assert.equal(actual, expected);Assert strict equality in Node.
assert.deepEqual(actual, expected);Assert deep structural equality.
node --testRun Node's built-in test runner.
test('adds numbers', () => { assert.equal(1 + 1, 2); });Basic Node test-runner example.
class MyElement extends HTMLElement { }Define a custom element class.
customElements.define('my-element', MyElement);Register a custom element.
this.attachShadow({ mode: 'open' })Create a shadow root.
this.connectedCallback = () => { }Conceptual lifecycle hook; normally define as method.
const ctx = canvas.getContext('2d');Get a 2D drawing context.
ctx.fillRect(10, 10, 100, 50);Draw a filled rectangle.
ctx.clearRect(0, 0, canvas.width, canvas.height);Clear the canvas.
ctx.fillText('Hello', 20, 30);Draw text.
ctx.beginPath(); ctx.moveTo(0,0); ctx.lineTo(100,100); ctx.stroke();Draw a line.
new Intl.NumberFormat('en-US').format(1234567)Format a number.
new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(19.99)Format currency.
new Intl.DateTimeFormat('en-US').format(new Date())Format a date.
new Intl.PluralRules('en-US').select(2)Select plural category.
const unique = [...new Set(items)];Remove duplicate values.
const sum = nums.reduce((a, b) => a + b, 0);Sum an array.
const max = Math.max(...nums);Find maximum numeric value.
const grouped = Object.groupBy(items, x => x.category);Group values by key in environments supporting Object.groupBy.
const counts = items.reduce((m, x) => (m[x] = (m[x] || 0) + 1, m), {});Count repeated values.
const sorted = [...items].sort((a,b) => a.localeCompare(b));Sort strings without mutating original array.
const byId = Object.fromEntries(items.map(x => [x.id, x]));Index objects by ID.
const first = items.find(predicate) ?? null;Get first matching item or null.
const params = Object.fromEntries(new URLSearchParams(location.search));Convert query parameters to an object.
const sleep = ms => new Promise(r => setTimeout(r, ms));Create an async sleep helper.
const clone = structuredClone(obj);Deep-clone supported structured data.
const text = ' hello world '.trim().replace(/\s+/g, ' ');Normalize whitespace.
0.1 + 0.2 === 0.3Floating-point arithmetic is approximate.
[] === []Different arrays are different object references.
{} === {}Different objects are different object references.
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i)); }var is function-scoped; use let for per-iteration bindings.
Array(10).map(...)Sparse arrays may skip callbacks; use Array.from({length:10}).
items.sort()Default sort is lexicographic, even for numbers.
parseInt('08')Always pass a radix for clarity: parseInt('08', 10).
JSON.stringify(undefined)Top-level undefined serializes to undefined, not JSON text.
element.innerHTML = userInputInjecting untrusted HTML can create XSS vulnerabilities.
await items.forEach(async item => ...)forEach does not await async callbacks; use for...of or Promise.all.