let obj = new Object;
obj.name = "Frank E. Stein";
obj.show = function() {
return "obj { " + `${obj.name}` + " }"
}
console.log(obj.show());
// output is: obj { Frank E. Stein }
onlinejsplayground.com
--- Values, variables, and scope ---
// Numbers, strings, booleans, null, undefined, BigInt, Symbol
let n = 42, s = "hi", ok = true, z = null;
// Prefer let/const over var (block vs function scope)
const PI = 3.1416; // cannot be reassigned
let count = 0; // can be reassigned
--- Expressions and operators ---
// Math, comparison, logical
1 + 2 * 3; // 7
10 ** 2; // 100 (exponent)
a === b; // strict equality (no coercion)
a && b || c; // short-circuiting
// Nullish coalescing & optional chaining
const name = user.name ?? "Anonymous";
const city = user.address?.city; // undefined if any link is missing
--- Control flow ---
if (x > 0) { ... } else { ... }
for (let i = 0; i < 3; i++) { ... }
for (const v of [1,2,3]) { ... } // iterable loop
while (cond) { ... }
switch (kind) {
case "cat": doCat(); break;
default: fallback();
}
--- Function declarations, expressions, lambdas ---
function add(a, b = 0) { return a + b; } // default param
const mul = function(a, b) { return a * b; }; // expression
const dbl = x => x * 2; // arrow (lexical `this`)
--- Objects and arrays ---
const person = { id: 1, name: "Ada" };
const team = ["A", "B", "C"];
// Destructuring
const { name } = person;
const [first, ...rest] = team;
// Shorthand & computed keys
const x = 1, y = 2;
const point = { x, y, ["p" + "3"]: 3 };
// Spread/merge
const withAge = { ...person, age: 36 };
const bigger = [...team, "D"];
--- Template literals ---
const who = "world";
const msg = `Hello, ${who}!
This spans multiple lines.`;
--- Classes (ES2015+) ---
class Counter {
#n = 0; // private field
inc() { this.#n++; }
get value() { return this.#n; }
static from(n) { const c = new Counter(); c.#n = n; return c; }
}
--- Modules ---
// export.js
export const PI = 3.14;
export default function area(r){ return PI * r * r; }
// import.js
import area, { PI } from "./export.js";
--- Promises and async/await ---
// Promise chain
fetch("/api/user")
.then(r => r.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// async/await
async function load() {
try {
const r = await fetch("/api/user");
const data = await r.json();
console.log(data);
} catch (e) {
console.error(e);
}
}
--- Errors and try/catch ---
try {
risky();
} catch (err) {
console.error(err.message);
} finally {
cleanup();
}
--- DOM basics ---
const btn = document.querySelector("#go");
btn.addEventListener("click", () => {
document.body.style.backgroundColor = "papayawhip";
});
--- Truthy / falsey & equality ---
// falsey: false, 0, -0, 0n, "", null, undefined, NaN
if ("0") { /* runs: non-empty strings are truthy */ }
// Prefer === to avoid coercion surprises
"5" == 5 // true (coerces)
"5" === 5 // false (strict)
<div id="demo" onclick="toggle('demo')">Hello World</div>
| Signature | Brief description | Example |
|---|---|---|
Static properties (on Object) | ||
Object.prototype | Base prototype of plain objects | Object.prototype.hasOwnProperty.call(o,'x') |
Object.length | Formal parameters count (1) | Object.length === 1 |
Object.name | Function name | Object.name === 'Object' |
Static methods (on Object) | ||
Object.assign(target, ...sources) | Shallow copy/merge | Object.assign({}, a, b) |
Object.create(proto[, props]) | Create with prototype | const o = Object.create(null) |
Object.defineProperty(obj, key, desc) | Define 1 property | Object.defineProperty(o,'id',{value:1,writable:false}) |
Object.defineProperties(obj, descs) | Define many | Object.defineProperties(o,{a:{value:1},b:{value:2}}) |
Object.entries(obj) | [[key,value]] array | Object.entries(o).forEach(([k,v])=>...) |
Object.fromEntries(iter) | Entries → object | Object.fromEntries(new URLSearchParams(qs)) |
Object.values(obj) | Enumerable values | Object.values(o).includes(42) |
Object.keys(obj) | Enumerable keys | for (const k of Object.keys(o)) {...} |
Object.getOwnPropertyNames(obj) | Own string keys | Object.getOwnPropertyNames(o) |
Object.getOwnPropertySymbols(obj) | Own symbol keys | Object.getOwnPropertySymbols(o) |
Object.getOwnPropertyDescriptor(obj, key) | Descriptor of key | Object.getOwnPropertyDescriptor(o,'x') |
Object.getOwnPropertyDescriptors(obj) | All descriptors | Object.getOwnPropertyDescriptors(o) |
Object.getPrototypeOf(obj) | Read prototype | Object.getPrototypeOf(o) === Foo.prototype |
Object.setPrototypeOf(obj, proto) | Set prototype | Object.setPrototypeOf(o, null) |
Object.is(a, b) | SameValue compare | Object.is(NaN, NaN) === true |
Object.seal(obj) | Block add/remove props | Object.seal(o) |
Object.isSealed(obj) | Sealed? | Object.isSealed(o) |
Object.freeze(obj) | Make immutable (shallow) | Object.freeze(config) |
Object.isFrozen(obj) | Frozen? | Object.isFrozen(config) |
Object.preventExtensions(obj) | Disallow new props | Object.preventExtensions(o) |
Object.isExtensible(obj) | Extensible? | Object.isExtensible(o) |
Object.hasOwn(obj, key) | Own key present? | Object.hasOwn(o, 'id') |
Prototype methods (on Object.prototype) | ||
obj.hasOwnProperty(key) | Own key check | o.hasOwnProperty('x') |
obj.propertyIsEnumerable(key) | Enumerable? | o.propertyIsEnumerable('x') |
obj.isPrototypeOf(value) | In prototype chain? | Foo.prototype.isPrototypeOf(inst) |
obj.toString() | Tag/legacy string | Object.prototype.toString.call([]) // "[object Array]" |
obj.toLocaleString() | Locale string | date.toLocaleString('en-US') |
obj.valueOf() | Primitive hint | new Number(5).valueOf() === 5 |
| Prototype properties / accessors | ||
obj.__proto__ (getter/setter) | Legacy proto access | obj.__proto__ = null (prefer get/setPrototypeOf) |
obj.constructor | Ref to constructor | o.constructor === Object |
| Legacy utilities (non-standard / discouraged) | ||
obj.__defineGetter__(key, fn) | Define getter | o.__defineGetter__('x', () => 42) |
obj.__defineSetter__(key, fn) | Define setter | o.__defineSetter__('x', v => log(v)) |
obj.__lookupGetter__(key) | Lookup getter | o.__lookupGetter__('x') |
obj.__lookupSetter__(key) | Lookup setter | o.__lookupSetter__('x') |
| Signature | Brief description | Example |
|---|---|---|
| Selection & traversal | ||
document.querySelector(sel) | First match | const el = qs('#app') |
document.querySelectorAll(sel) | NodeList of matches | [...qsa('.item')] |
document.getElementById(id) | By id | gebi('nav') |
element.closest(sel) | Nearest ancestor match | btn.closest('form') |
element.matches(sel) | Element matches selector? | if (el.matches('.active')) { … } |
element.parentElement | Parent node | el.parentElement.remove() |
element.children | HTMLCollection of children | [...el.children].length |
| Events | ||
element.addEventListener(type, fn, opts) | Listen for events | el.addEventListener('click', onClick, { once:true }) |
element.removeEventListener(type, fn, opts) | Stop listening | el.removeEventListener('click', onClick) |
element.dispatchEvent(evt) | Fire custom event | el.dispatchEvent(new Event('refresh')) |
| Classes & attributes | ||
element.classList.add(...tokens) | Add class(es) | el.classList.add('active') |
element.classList.remove(...tokens) | Remove class(es) | el.classList.remove('hidden') |
element.classList.toggle(token[, force]) | Toggle class | el.classList.toggle('open', isOpen) |
element.className | Class string | el.className = 'card raised' |
element.setAttribute(name, value) | Set attribute | el.setAttribute('aria-live','polite') |
element.getAttribute(name) | Read attribute | el.getAttribute('role') |
element.removeAttribute(name) | Remove attribute | el.removeAttribute('disabled') |
element.hasAttribute(name) | Has attribute? | el.hasAttribute('hidden') |
| Content & DOM mutation | ||
element.textContent | Set/read text | el.textContent = 'Hello' |
element.innerHTML | Set/read HTML | el.innerHTML = '<b>Hi</b>' |
element.insertAdjacentHTML(pos, html) | Insert HTML | el.insertAdjacentHTML('beforeend','<li>…</li>') |
element.append(...nodes) | Append nodes/text | el.append(child) |
element.prepend(...nodes) | Prepend nodes | el.prepend(title) |
element.replaceWith(node) | Replace self | el.replaceWith(newEl) |
element.remove() | Detach from DOM | el.remove() |
document.createElement(tag) | New element | const div = ce('div') |
| Styles | ||
element.style.prop | Inline style property | el.style.backgroundColor = '#222' |
style.setProperty(name, value, priority?) | Set (incl. !important) | el.style.setProperty('margin','0','important') |
style.getPropertyValue(name) | Read inline value | el.style.getPropertyValue('--gap') |
getComputedStyle(el[, pseudo]) | Resolved styles | getComputedStyle(el).color |
| Stylesheets (CSSOM) | ||
document.styleSheets | List of sheets | const sheet = document.styleSheets[0] |
sheet.insertRule(rule, i) | Add CSS rule | sheet.insertRule('.box{gap:8px}', sheet.cssRules.length) |
sheet.deleteRule(i) | Remove rule | sheet.deleteRule(0) |
new CSSStyleSheet() | Constructable sheet | const s = new CSSStyleSheet() |
sheet.replaceSync(text) | Replace contents | s.replaceSync(':root{--c:#09f}') |
document.adoptedStyleSheets | Adopt sheets | document.adoptedStyleSheets = [...document.adoptedStyleSheets, s] |
| Geometry & scrolling | ||
element.getBoundingClientRect() | Box metrics | const {top} = el.getBoundingClientRect() |
element.scrollIntoView(opts) | Scroll to element | el.scrollIntoView({ behavior:'smooth' }) |
window.scrollX / scrollY | Page scroll offsets | if (scrollY > 100) { … } |
| Media queries & animation | ||
matchMedia(query) | Watch media state | matchMedia('(prefers-color-scheme:dark)').matches |
element.animate(keyframes, options) | Web Animations | el.animate({opacity:[0,1]}, 300) |
| Forms | ||
form.requestSubmit() | Programmatic submit | form.requestSubmit() |
form.reset() | Reset controls | form.reset() |
input.value | Read/write value | name.value = 'Ada' |
checkbox.checked | Boolean state | agree.checked = true |
| Storage & network | ||
localStorage.getItem/setItem/removeItem | Key-value storage | localStorage.setItem('theme','dark') |
sessionStorage.getItem/… | Per-tab storage | sessionStorage.getItem('token') |
fetch(url, options) | HTTP requests | await fetch('/api/data') |
| Timing | ||
setTimeout(fn, ms) / clearTimeout(id) | Delay a task | const id = setTimeout(run, 200) |
setInterval(fn, ms) / clearInterval(id) | Repeat task | setInterval(tick, 1000) |
requestAnimationFrame(fn) / cancelAnimationFrame(id) | Frame-synced | raf = requestAnimationFrame(step) |
class Point {
// public instance fields (per instance, on `this`)
x = 0;
y = 0;
constructor(x, y) { // runs on `new Point(...)`
this.x = x; this.y = y;
}
// prototype method (shared by instances)
length() { return Math.hypot(this.x, this.y); }
// getter/setter
get r() { return this.length(); }
set r(v) { const a = Math.atan2(this.y, this.x); this.x = v*Math.cos(a); this.y = v*Math.sin(a); }
// static method (on the class constructor)
static origin() { return new Point(0, 0); }
}
class Counter {
#value = 0; // private instance field
static #MAX = 1_000_000; // private static field
get value() { return this.#value; }
#clamp(n) { return Math.min(n, Counter.#MAX); } // private method
increment() { this.#value = this.#clamp(this.#value + 1); }
static from(n) { const c = new Counter(); c.#value = c.#clamp(n); return c; }
}
// Presence check (only inside class that declares #value):
// if (#value in someObj) { ... }
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a noise.`; }
}
class Dog extends Animal {
constructor(name) { super(name); } // must call super() before using `this`
speak() { return `${super.speak()} Woof!`; } // call base method
}
class Config {
static base = '/api';
static #token;
static { // runs once when class is evaluated
this.#token = crypto.randomUUID?.() ?? 'dev-token';
}
static authHeader() { return { Authorization: `Bearer ${this.#token}` }; }
}
const Widget = class NamedWidget { /* ... */ }; // name usable inside the class body
class Greeter {
['say' + 'Hi']() { return 'hi'; } // computed method name
static ['v' + 1] = 2; // computed static field
}
class Timer {
start = performance.now();
label = `t-${this.start | 0}`;
}
class Base {
constructor() {
if (new.target === Base) throw new TypeError('Abstract');
}
}
class Button {
// Arrow keeps `this` bound without manual .bind()
handleClick = (e) => { this.count++; };
count = 0;
}
| CSS property | JS (element.style.*) | Example (JS) |
|---|---|---|
| --custom-prop | setProperty / getPropertyValue | el.style.setProperty('--brand', '#0af') |
| all | all | el.style.all = 'unset' |
| color | color | el.style.color = 'rebeccapurple' |
| background | background | el.style.background = 'linear-gradient(#000,#333)' |
| background-color | backgroundColor | el.style.backgroundColor = 'tomato' |
| background-image | backgroundImage | el.style.backgroundImage = "url('bg.png')" |
| background-position | backgroundPosition | el.style.backgroundPosition = 'center 20%' |
| background-size | backgroundSize | el.style.backgroundSize = 'cover' |
| background-repeat | backgroundRepeat | el.style.backgroundRepeat = 'no-repeat' |
| background-clip | backgroundClip | el.style.backgroundClip = 'text' |
| background-origin | backgroundOrigin | el.style.backgroundOrigin = 'content-box' |
| opacity | opacity | el.style.opacity = '0.7' |
| font | font | el.style.font = "italic 600 1rem/1.4 Inter" |
| font-family | fontFamily | el.style.fontFamily = "Inter, system-ui, sans-serif" |
| font-size | fontSize | el.style.fontSize = '18px' |
| font-weight | fontWeight | el.style.fontWeight = '700' |
| font-style | fontStyle | el.style.fontStyle = 'oblique' |
| font-stretch | fontStretch | el.style.fontStretch = 'condensed' |
| font-variant | fontVariant | el.style.fontVariant = 'small-caps' |
| line-height | lineHeight | el.style.lineHeight = '1.6' |
| letter-spacing | letterSpacing | el.style.letterSpacing = '.02em' |
| word-spacing | wordSpacing | el.style.wordSpacing = '.1em' |
| text-align | textAlign | el.style.textAlign = 'center' |
| text-decoration | textDecoration | el.style.textDecoration = 'underline wavy' |
| text-decoration-color | textDecorationColor | el.style.textDecorationColor = '#09f' |
| text-transform | textTransform | el.style.textTransform = 'uppercase' |
| text-overflow | textOverflow | el.style.textOverflow = 'ellipsis' |
| white-space | whiteSpace | el.style.whiteSpace = 'nowrap' |
| word-break | wordBreak | el.style.wordBreak = 'break-word' |
| hyphens | hyphens | el.style.hyphens = 'auto' |
| text-shadow | textShadow | el.style.textShadow = '0 1px 2px rgba(0,0,0,.3)' |
| direction | direction | el.style.direction = 'rtl' |
| writing-mode | writingMode | el.style.writingMode = 'vertical-rl' |
| tab-size | tabSize | el.style.tabSize = '4' |
| caret-color | caretColor | el.style.caretColor = 'auto' |
| accent-color | accentColor | el.style.accentColor = 'hotpink' |
| user-select | userSelect | el.style.userSelect = 'none' |
| width | width | el.style.width = '320px' |
| height | height | el.style.height = '200px' |
| min-width | minWidth | el.style.minWidth = '10rem' |
| max-width | maxWidth | el.style.maxWidth = '60ch' |
| min-height | minHeight | el.style.minHeight = '100vh' |
| max-height | maxHeight | el.style.maxHeight = '80vh' |
| margin | margin | el.style.margin = '1rem auto' |
| padding | padding | el.style.padding = '16px' |
| border | border | el.style.border = '1px solid #ddd' |
| border-radius | borderRadius | el.style.borderRadius = '12px' |
| border-color | borderColor | el.style.borderColor = '#ccc' |
| border-width | borderWidth | el.style.borderWidth = '2px' |
| outline | outline | el.style.outline = '2px solid #09f' |
| outline-offset | outlineOffset | el.style.outlineOffset = '2px' |
| box-sizing | boxSizing | el.style.boxSizing = 'border-box' |
| box-shadow | boxShadow | el.style.boxShadow = '0 4px 12px rgba(0,0,0,.15)' |
| aspect-ratio | aspectRatio | el.style.aspectRatio = '16 / 9' |
| display | display | el.style.display = 'grid' |
| visibility | visibility | el.style.visibility = 'hidden' |
| position | position | el.style.position = 'absolute' |
| inset | inset | el.style.inset = '0' |
| top / right / bottom / left | top / right / bottom / left | el.style.top = '10px' |
| z-index | zIndex | el.style.zIndex = '10' |
| float | cssFloat | el.style.cssFloat = 'left' |
| clear | clear | el.style.clear = 'both' |
| overflow | overflow | el.style.overflow = 'auto' |
| overflow-x | overflowX | el.style.overflowX = 'hidden' |
| overflow-y | overflowY | el.style.overflowY = 'scroll' |
| clip-path | clipPath | el.style.clipPath = 'inset(10px)' |
| isolation | isolation | el.style.isolation = 'isolate' |
| pointer-events | pointerEvents | el.style.pointerEvents = 'none' |
| cursor | cursor | el.style.cursor = 'pointer' |
| filter | filter | el.style.filter = 'grayscale(1)' |
| backdrop-filter | backdropFilter | el.style.backdropFilter = 'blur(8px)' |
| contain | contain | el.style.contain = 'layout paint' |
| will-change | willChange | el.style.willChange = 'transform' |
| mix-blend-mode | mixBlendMode | el.style.mixBlendMode = 'multiply' |
| flex-direction | flexDirection | el.style.flexDirection = 'row-reverse' |
| flex-wrap | flexWrap | el.style.flexWrap = 'wrap' |
| flex-flow | flexFlow | el.style.flexFlow = 'row wrap' |
| justify-content | justifyContent | el.style.justifyContent = 'space-between' |
| align-items | alignItems | el.style.alignItems = 'center' |
| align-content | alignContent | el.style.alignContent = 'space-around' |
| gap | gap | el.style.gap = '1rem' |
| row-gap | rowGap | el.style.rowGap = '.5rem' |
| column-gap | columnGap | el.style.columnGap = '2rem' |
| order | order | child.style.order = '2' |
| flex-grow | flexGrow | child.style.flexGrow = '1' |
| flex-shrink | flexShrink | child.style.flexShrink = '0' |
| flex-basis | flexBasis | child.style.flexBasis = '200px' |
| align-self | alignSelf | child.style.alignSelf = 'flex-end' |
| place-content | placeContent | el.style.placeContent = 'center' |
| place-items | placeItems | el.style.placeItems = 'start' |
| place-self | placeSelf | child.style.placeSelf = 'stretch' |
| grid-template-columns | gridTemplateColumns | el.style.gridTemplateColumns = 'repeat(3, 1fr)' |
| grid-template-rows | gridTemplateRows | el.style.gridTemplateRows = 'auto 1fr auto' |
| grid-template-areas | gridTemplateAreas | el.style.gridTemplateAreas = '"h h" "m s" "f f"' |
| grid-auto-columns | gridAutoColumns | el.style.gridAutoColumns = 'minmax(0,1fr)' |
| grid-auto-rows | gridAutoRows | el.style.gridAutoRows = 'minmax(2rem, auto)' |
| grid-auto-flow | gridAutoFlow | el.style.gridAutoFlow = 'row dense' |
| grid-column | gridColumn | item.style.gridColumn = '1 / 3' |
| grid-row | gridRow | item.style.gridRow = '2 / 4' |
| grid-area | gridArea | item.style.gridArea = 'header' |
| transform | transform | el.style.transform = 'translateY(10px) scale(.9)' |
| transform-origin | transformOrigin | el.style.transformOrigin = '50% 0' |
| transform-style | transformStyle | el.style.transformStyle = 'preserve-3d' |
| perspective | perspective | el.style.perspective = '600px' |
| perspective-origin | perspectiveOrigin | el.style.perspectiveOrigin = 'center' |
| backface-visibility | backfaceVisibility | el.style.backfaceVisibility = 'hidden' |
| transition | transition | el.style.transition = 'opacity .3s ease' |
| transition-property | transitionProperty | el.style.transitionProperty = 'transform' |
| transition-duration | transitionDuration | el.style.transitionDuration = '200ms' |
| transition-timing-function | transitionTimingFunction | el.style.transitionTimingFunction = 'cubic-bezier(.2,.8,.2,1)' |
| transition-delay | transitionDelay | el.style.transitionDelay = '50ms' |
| animation-name | animationName | el.style.animationName = 'pulse' |
| animation-duration | animationDuration | el.style.animationDuration = '1.2s' |
| animation-iteration-count | animationIterationCount | el.style.animationIterationCount = 'infinite' |
| animation-direction | animationDirection | el.style.animationDirection = 'alternate' |
| animation-timing-function | animationTimingFunction | el.style.animationTimingFunction = 'ease-in-out' |
| animation-fill-mode | animationFillMode | el.style.animationFillMode = 'both' |
| animation-play-state | animationPlayState | el.style.animationPlayState = 'paused' |
| object-fit | objectFit | img.style.objectFit = 'cover' |
| object-position | objectPosition | img.style.objectPosition = '50% 50%' |
| image-rendering | imageRendering | el.style.imageRendering = 'pixelated' |
| list-style | listStyle | el.style.listStyle = 'square inside' |
| list-style-type | listStyleType | el.style.listStyleType = 'decimal' |
| list-style-position | listStylePosition | el.style.listStylePosition = 'inside' |
| list-style-image | listStyleImage | el.style.listStyleImage = "url('bullet.svg')" |
| border-collapse | borderCollapse | el.style.borderCollapse = 'collapse' |
| table-layout | tableLayout | el.style.tableLayout = 'fixed' |
| empty-cells | emptyCells | el.style.emptyCells = 'hide' |
| caption-side | captionSide | el.style.captionSide = 'bottom' |
| columns | columns | el.style.columns = '2 18rem' |
| column-count | columnCount | el.style.columnCount = '3' |
| column-gap | columnGap | el.style.columnGap = '1.5rem' |
| column-width | columnWidth | el.style.columnWidth = '20rem' |
| column-rule | columnRule | el.style.columnRule = '1px solid #ddd' |
| scroll-behavior | scrollBehavior | el.style.scrollBehavior = 'smooth' |
| overscroll-behavior | overscrollBehavior | el.style.overscrollBehavior = 'contain' |
| scroll-snap-type | scrollSnapType | el.style.scrollSnapType = 'x mandatory' |
| scroll-snap-align | scrollSnapAlign | child.style.scrollSnapAlign = 'center' |
| scroll-margin | scrollMargin | el.style.scrollMargin = '2rem' |
| scroll-padding | scrollPadding | el.style.scrollPadding = '2rem' |
| appearance | appearance | el.style.appearance = 'none' |
| visibility | visibility | el.style.visibility = 'visible' |
| resize | resize | el.style.resize = 'both' |
| outline-style | outlineStyle | el.style.outlineStyle = 'dashed' |
| outline-width | outlineWidth | el.style.outlineWidth = '3px' |
| outline-color | outlineColor | el.style.outlineColor = 'crimson' |
| (any property) + !important | setProperty | el.style.setProperty('margin','0','important') |
| Context / API | Method / Property | Purpose / Mini example |
|---|---|---|
Inline styles (via element.style) — CSSStyleDeclaration | ||
| Inline style object | element.style | Access the element’s inline styles (writeable). |
| Set property | style.setProperty(name, value, [priority]) | el.style.setProperty('--brand','#0af','important') |
| Get property | style.getPropertyValue(name) | style.getPropertyValue('--brand') → #0af |
| Get priority | style.getPropertyPriority(name) | Returns 'important' or '' |
| Remove property | style.removeProperty(name) | style.removeProperty('--brand') |
| Enumerate | style.length, style.item(i) | Count & iterate property names. |
| Inline CSS text | style.cssText | Read/replace all inline styles: style.cssText = 'color:red;' |
| Direct assignment | style.backgroundColor (camelCase) | el.style.backgroundColor = 'tomato' |
Class-based styling — DOMTokenList via element.classList | ||
| Token list | element.classList | Live list of classes. |
| Add / remove | add(...tokens), remove(...tokens) | el.classList.add('active','wide') |
| Toggle | toggle(token[, force]) | el.classList.toggle('hidden', false) |
| Replace | replace(old, next) | el.classList.replace('old','new') |
| Query | contains(token), item(i), length | Test/inspect classes. |
| Iterate | forEach, values(), entries() | Loop classes. |
| Whole string | element.className | Get/set the raw class attribute. |
| Computed styles — read resolved values | ||
| Get computed | getComputedStyle(element[, pseudo]) | const cs = getComputedStyle(el) → cs.getPropertyValue('color') |
| Style attribute (raw) | ||
| Set / get / remove | setAttribute('style', cssText), getAttribute('style'), removeAttribute('style') | el.setAttribute('style','color:rebeccapurple') |
| Stylesheets & rules — CSSOM | ||
| All sheets | document.styleSheets (StyleSheetList) | Enumerate attached stylesheets (including <style>/<link>). |
| Insert / delete rule | CSSStyleSheet.insertRule(rule, i), deleteRule(i) | sheet.insertRule('.box{gap:1rem}', sheet.cssRules.length) |
| Replace text | CSSStyleSheet.replace(text), replaceSync(text) | Swap entire sheet (constructable sheets support both). |
| Rules list | sheet.cssRules (CSSRuleList) | Iterate rules: sheet.cssRules[i] |
| Enable/disable | sheet.disabled | Temporarily turn a stylesheet off. |
| Style rule | CSSStyleRule.selectorText, .style | Change selector or declarations of a rule. |
| Keyframes (sheet) | CSSKeyframesRule.appendRule(), deleteRule(), findRule() | Manipulate @keyframes at runtime. |
| Media rule | CSSMediaRule.conditionText, .cssRules | Inspect rules under a media query. |
| Constructable stylesheets (modern) | ||
| Create | new CSSStyleSheet() | Create a sheet in JS. |
| Populate | sheet.replaceSync(text) / replace(text) | sheet.replaceSync(':root{--c:#09f}') |
| Adopt (doc) | document.adoptedStyleSheets | document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet] |
| Adopt (shadow) | shadowRoot.adoptedStyleSheets | Share sheets across Shadow DOM roots. |
| CSS Custom Properties | ||
| Set / get / remove | style.setProperty('--x','10px'), getPropertyValue('--x'), removeProperty('--x') | Scope to element (or document.documentElement for global). |
| CSS Typed OM (optional, newer) | ||
| Inline map | element.attributeStyleMap | Write typed values: el.attributeStyleMap.set('opacity', 0.7) |
| Read computed map | element.computedStyleMap() | el.computedStyleMap().get('width') → typed value. |
| Map ops | set, append, delete, get, getAll, has, clear | Manage style entries as a map. |
| Media queries in JS | ||
| Query | matchMedia(query) | const m = matchMedia('(prefers-color-scheme:dark)') |
| Listen | m.addEventListener('change', fn) | Respond to media changes; old: addListener/removeListener. |
| Web Animations API (programmatic CSS-like animation) | ||
| Animate | element.animate(keyframes, options) | el.animate([{opacity:0},{opacity:1}], {duration:300}) → Animation |
| Control | animation.play(), pause(), reverse(), finish(), cancel() | Imperatively control visual state. |
| Category / Interface | Key Methods / Properties | Description | Example |
|---|---|---|---|
|
appendChild removeChild replaceChild cloneNode normalize |
Base of DOM tree. Core manipulation of nodes (adding/removing/cloning) and normalization. |
const p = document.createElement('p'); document.body.appendChild(p); |
|
|
getAttribute / setAttribute / removeAttribute / hasAttribute querySelector / querySelectorAll closest / matches |
Represents element nodes; attribute access, querying descendants, selector matching, and traversal. |
const el = document.querySelector('.item'); if (el.matches('.active')) { /*...*/ } |
|
|
focus() / blur() / click() scrollIntoView() getBoundingClientRect() dataset insertAdjacentHTML / insertAdjacentElement |
HTML-specific element features: focus control, geometry, data-* access, and convenient insertion. |
el.dataset.id = '42'; el.scrollIntoView(); |
|
|
createElement createTextNode getElementById querySelectorAll body / head / documentElement |
Root of DOM; create nodes, access top-level elements, and perform global queries. |
const div = document.createElement('div'); document.body.appendChild(div); |
|
|
addEventListener removeEventListener dispatchEvent |
Event handling mechanism used by nodes: subscribe, unsubscribe, and emit events. |
el.addEventListener('click', e => console.log(e)); el.dispatchEvent(new Event('custom')); |
|
|
parentNode / children / childNodes nextSibling / previousSibling replaceWith / remove / prepend / append |
Navigate and modify the DOM structure, including inserting and replacing elements. | el.replaceWith(document.createElement('span')); | |
|
querySelector / querySelectorAll getElementById / getElementsByClassName / getElementsByTagName |
Find elements using CSS selectors or legacy collection methods (some live). | const items = document.getElementsByClassName('card'); | |
|
setAttribute / getAttribute property access (e.g., el.value) dataset |
Attributes are markup; properties are JS object fields. Reflection patterns sync them. |
el.setAttribute('data-role','admin'); console.log(el.dataset.role); |
|
|
new Event / MouseEvent / CustomEvent event.preventDefault() event.stopPropagation() |
Creation, dispatch, and handling of events. Supports bubbling, capturing, and delegation. | el.addEventListener('submit', e => { e.preventDefault(); }); | |
|
attachShadow({mode}) <slot> |
Encapsulation of markup/styles; slotting projects light DOM content into shadow DOM. |
const root = el.attachShadow({mode:'open'}); root.innerHTML = '<slot></slot>'; |
|
|
class X extends HTMLElement customElements.define(name, constructor) connectedCallback / disconnectedCallback / attributeChangedCallback / adoptedCallback |
Define new HTML tags with lifecycle hooks and encapsulated behavior. | customElements.define('my-widget', MyWidget); | |
|
new MutationObserver(callback) observe(target, options) |
Watch DOM changes (child list, attributes, subtree) and react programmatically. |
const obs = new MutationObserver(m => console.log(m)); obs.observe(el, { childList: true }); |
|
|
getBoundingClientRect() window.getComputedStyle() |
Measure element size/position and computed styles, essential for layout logic. | const rect = el.getBoundingClientRect(); | |
|
classList (add/toggle/contains/remove) dataset |
Utility accessors for manipulating CSS classes and data-* attributes easily. | el.classList.toggle('active'); | |
|
<template> template.content.cloneNode(true) |
Define inert HTML fragments to instantiate multiple times without executing scripts. |
const tpl = document.getElementById('tpl'); document.body.appendChild(tpl.content.cloneNode(true)); |
|
| createDocumentFragment() | Batch DOM insertions efficiently; fragment isn't rendered until appended. |
const frag = document.createDocumentFragment(); frag.appendChild(document.createElement('div')); document.body.appendChild(frag); |
|
| new CustomEvent(type, { detail }) | Dispatch events with structured payloads. | el.dispatchEvent(new CustomEvent('update', { detail: { id: 5 } })); |
| Window API (signature) | Brief description | Example |
|---|---|---|
| Identity & globals | ||
window / self | Global object in browsers | self === window |
top, parent, opener | Frame tree refs | if (window !== top) {/* in iframe */} |
frames (array-like), length, frames[i] / frames['name'] |
Child frame windows collection & count; access by index or name (alias: window[i]). Cross-origin rules apply. |
for (let i = 0; i < frames.length; i++) frames[i].postMessage('ping','*') |
name | Window name (targeting) | window.name = 'preview' |
origin | Scheme+host+port | console.log(location.origin) |
| Document & DOM | ||
document | Active document | document.title = 'Hello' |
getSelection() | Current text selection | const sel = getSelection() |
customElements | Custom elements registry | customElements.define('x-box', Box) |
getComputedStyle(el[, pseudo]) | Resolved styles | getComputedStyle(el).color |
| Navigation | ||
location | URL / navigation | location.href = '/login' |
history | Session history | history.back(), history.go(1) |
open(url, target, features) | Open new window/tab | open('/help','_blank') |
close() | Close this window | window.close() |
stop() | Stop loading | window.stop() |
| Focus, dialogs, print | ||
focus(), blur() | Focus/defocus window | window.focus() |
alert(msg) | Modal alert | alert('Saved') |
confirm(msg) | OK/Cancel dialog | if (confirm('Delete?')) ... |
prompt(msg[, def]) | Prompt for input | const n = prompt('Name?') |
print() | Open print dialog | print() |
| Timers & scheduling | ||
setTimeout(fn, ms) / clearTimeout(id) | Run once after delay | const t = setTimeout(run, 200) |
setInterval(fn, ms) / clearInterval(id) | Run repeatedly | setInterval(tick, 1000) |
queueMicrotask(fn) | Microtask queue | queueMicrotask(flush) |
requestAnimationFrame(fn) / cancelAnimationFrame(id) | Frame-synced callback | raf = requestAnimationFrame(step) |
requestIdleCallback(fn) / cancelIdleCallback(id) | Idle-time work | requestIdleCallback(render) |
| Size, screen & viewport | ||
innerWidth, innerHeight | Viewport size | if (innerWidth < 768) {...} |
outerWidth, outerHeight | Window outer size | console.log(outerHeight) |
devicePixelRatio | CSS px → device px | if (devicePixelRatio>1) {...} |
screen | Screen info | screen.availWidth |
visualViewport | Visual viewport API | visualViewport.scale |
| Scrolling | ||
scrollX / pageXOffset, scrollY / pageYOffset | Scroll offsets | if (scrollY > 100) ... |
scrollTo(x,y|opts), scrollBy(dx,dy|opts), scroll(opts) | Programmatic scroll | scrollTo({top:0, behavior:'smooth'}) |
| Events | ||
addEventListener(type, fn[, opts]) | Listen for events | addEventListener('resize', onResize) |
removeEventListener(...) | Stop listening | removeEventListener('resize', onResize) |
dispatchEvent(evt) | Fire custom event | dispatchEvent(new Event('refresh')) |
| Common window events | Lifecycle/connectivity | load, beforeunload, hashchange, popstate, online, offline, storage |
| Error handlers | Global error capture | onerror, onunhandledrejection |
| Messaging & queries | ||
postMessage(msg, targetOrigin[, transfer]) | X-doc messaging | other.postMessage({ok:true}, '*') |
matchMedia(query) | Media query state | matchMedia('(prefers-color-scheme:dark)').matches |
| Networking & streams | ||
fetch(input, init) | HTTP requests | await fetch('/api') |
AbortController, AbortSignal | Cancel fetch/tasks | const c=new AbortController(); fetch(u,{signal:c.signal}) |
WebSocket | Realtime socket | new WebSocket('wss://…') |
| Storage & data | ||
localStorage / sessionStorage | Key/value storage | localStorage.setItem('theme','dark') |
indexedDB | Client DB (async) | indexedDB.open('db',1) |
caches | CacheStorage | await caches.open('v1') |
structuredClone(value[, options]) | Deep structured clone | const copy = structuredClone(obj) |
| Crypto & performance | ||
crypto.getRandomValues(typedArray) | CSPRNG | crypto.getRandomValues(new Uint8Array(16)) |
crypto.subtle | Web Crypto (SubtleCrypto) | await crypto.subtle.digest('SHA-256', data) |
performance | High-res timings | performance.now() |
| URLs & encoding | ||
URL, URLSearchParams | URL parsing/build | new URL('/p', location.origin) |
atob(str) / btoa(str) | Base64 decode/encode | atob('SGk=') |
Blob, File, FileReader | Binary/file APIs | new Blob(['hi']) |
| Workers & channels | ||
Worker(url[, opts]) | Background thread | new Worker('/w.js') |
SharedWorker(url[, opts]) | Shared background | new SharedWorker('/sw.js') |
BroadcastChannel(name) | Tab-to-tab messaging | new BroadcastChannel('sync') |
| Environment & device | ||
navigator | Env capabilities | navigator.onLine |
screen.orientation | Screen orientation | screen.orientation.type |
| Common handler properties | ||
onload, onbeforeunload, onresize, onscroll | Assign event handlers | onresize = () => layout() |
onmessage, onerror, onunhandledrejection | Messaging & errors | onmessage = e => console.log(e.data) |
| Feature | Example | Description | Default | Modern Support |
|---|---|---|---|---|
| width | width=600 | Sets content area width in pixels. | Browser default size | Yes |
| height | height=400 | Sets content area height in pixels. | Browser default size | Yes |
| left | left=100 | Distance from left edge of screen. | Centered | Yes |
| top | top=50 | Distance from top edge of screen. | Centered | Yes |
| menubar | menubar=no | Show or hide browser menu bar. | yes | Partial |
| toolbar | toolbar=no | Show or hide navigation toolbar. | yes | Partial |
| location | location=no | Show or hide address bar. | yes | Partial |
| status | status=no | Show or hide status bar at bottom. | yes | Partial |
| scrollbars | scrollbars=yes | Allow or disallow scrollbars if needed. | yes | Yes |
| resizable | resizable=yes | Allow or prevent window resizing. | yes | Yes |
| fullscreen | fullscreen=yes | Open in full screen mode. | no | Limited |
| noopener | noopener | Block access to window.opener. |
no | Yes |
| noreferrer | noreferrer | No Referer header; blocks opener. |
no | Yes |
| directories | directories=no | Old: control bookmarks bar visibility. | yes | No |
| titlebar | titlebar=no | Old: hide window title bar. | yes | No |
| copyhistory | copyhistory=yes | Copy session history from source window. | no | Limited |
| Reference | Comments |
|---|---|
| Understanding data types in JavaScript | Clear and complete |
| Understanding Objects in JavaScript | Author Tania Rascia is a developer with a gift for explaining technical topics very clearly. |
| Prototypes and Inheritance | Tania Rascia describes the JavaScript inheritance model in a thorough but simple way. |
| Modules, Import, and Export | Modules help us factor complex code into simpler parts. |
| Event Loop, Callbacks, Promises, and Async/Await | How JavaScript reacts to user events. |
| JavaScript tutorials list | Contains links to the previous articles and many more. |
| ECMAScript® 2025 Language Specification (ECMA-262, 16th ed.) | Normative HTML spec for the current ECMAScript edition (June 2025). |
| ECMA-262 Living Draft (Editor’s draft) | Continuously updated draft reflecting approved and in-flight changes. |
| MDN JavaScript Reference | Authoritative, task-oriented reference with examples and caveats. |
| MDN JavaScript Guide | Big-picture language guide with how-tos and best practices. |
| TC39 ECMAScript Proposals (Stage 2+) | Tracks features likely to land; useful for seeing what’s coming. |