← All guides

Programmer’s Reference

JavaScript

Add browser behavior with small, understandable examples.

Modern browser JavaScript. DOM examples require matching HTML elements. Browser and server JavaScript have different APIs.

22 entries · Essentials first · Reviewed October 5, 2026

Glossary: commands, keywords & terms

Select a term for its definition, syntax, example, and common mistakes.

Keywords and syntax

if / else

Choose a branch according to a truthy or falsey condition.

JavaScript code
const count = 3;
if (count > 0) {
  console.log('Some');
} else {
  console.log('None');
}

Practical useUse this construct in your own practice project.

Common mistakesUse === for strict comparison; = performs assignment.

Source: developer.mozilla.org documentation

|| (logical OR)

Return the first truthy operand, or the second operand.

JavaScript code
const nickname = '';
const label = nickname || 'Guest';
console.log(label);

Practical useUse this construct in your own practice project.

Common mistakesZero and empty strings trigger the fallback too; use ?? when only null/undefined should.

Source: developer.mozilla.org documentation

&& (logical AND)

Return the first falsey operand, or the second operand.

JavaScript code
const ready = true;
const allowed = false;
if (ready && allowed) { console.log('Proceed'); }

Practical useUse this construct in your own practice project.

Common mistakes&& returns an operand and short-circuits; & is bitwise.

Source: developer.mozilla.org documentation

! (logical NOT)

Negate the truthiness of a value.

JavaScript code
const ready = false;
if (!ready) { console.log('Waiting'); }

Practical useUse this construct in your own practice project.

Common mistakesNonempty strings such as "false" are truthy.

Source: developer.mozilla.org documentation

for

Repeat using initialization, a test, and an update.

JavaScript code
for (let i = 0; i < 3; i++) {
  console.log(i);
}

Practical useUse this construct in your own practice project.

Common mistakesUse let for the changing counter; check the stopping condition.

Source: developer.mozilla.org documentation

for...of

Iterate over values of an iterable.

JavaScript code
for (const name of ['Demo', 'Example']) {
  console.log(name);
}

Practical useUse this construct in your own practice project.

Common mistakesfor...in iterates enumerable property keys, not array values.

Source: developer.mozilla.org documentation

while / do...while

while checks before the body; do...while runs the body at least once.

JavaScript code
let attempt = 0;
while (attempt < 3) { attempt++; }
do { attempt--; } while (attempt > 0);

Practical useUse this construct in your own practice project.

Common mistakesInclude the final semicolon in do...while and avoid endless loops.

Source: developer.mozilla.org documentation

switch / case / default

Select a matching case using strict comparison.

JavaScript code
const state = 'ready';
switch (state) {
  case 'ready': console.log('Ready'); break;
  default: console.log('Unknown');
}

Practical useUse this construct in your own practice project.

Common mistakesMissing break allows fallthrough into later cases.

Source: developer.mozilla.org documentation

try / catch / finally / throw

Handle an exception and perform cleanup.

JavaScript code
try {
  throw new Error('Demo');
} catch (error) {
  console.log('Handled');
} finally {
  console.log('Cleanup');
}

Practical useUse this construct in your own practice project.

Common mistakesDo not silently swallow unexpected failures or expose confidential error details.

Source: developer.mozilla.org documentation

Essentials

const, let, and template strings

Use const for bindings that do not change and let for values you reassign.

JavaScript code
const site = 'Demo';
let checks = 0;
checks += 1;
console.log(`${site}: ${checks} checks`);

Practical useFormat a demo service summary.

Common mistakesconst prevents reassignment but does not freeze an object. Use === when coercion is unwanted.

Source: developer.mozilla.org documentation

Objects, arrays, and filter

Filter an array of objects to keep enabled records.

JavaScript code
const sites = [{name: 'Demo', enabled: true}];
const enabled = sites.filter(site => site.enabled === true);
console.log(enabled);

Practical useFilter a sanitized site list in an application view.

Common mistakesfilter returns a new array. Do not confuse = assignment with === comparison.

Source: developer.mozilla.org documentation

DOM and events

Select and update an element

Find an existing element and set plain text without interpreting it as HTML.

JavaScript code
const status = document.querySelector('#demo-status');
if (status) status.textContent = 'Check complete';

Practical useUpdate a status label in a demo application.

Common mistakesquerySelector can return null. Avoid inserting untrusted content with innerHTML. Run after the element exists.

Source: developer.mozilla.org documentation

Listen for a button click

Attach a click listener to an existing button.

JavaScript code
const button = document.querySelector('#demo-refresh');
button?.addEventListener('click', () => {
  console.log('Refresh requested');
});

Practical useWire a prototype refresh button to reviewed application logic.

Common mistakesUse a real button for keyboard support. This logs an event; it does not execute a server operation.

Source: developer.mozilla.org documentation

Async and data

Fetch JSON and handle failures

Load a local JSON fixture, check HTTP status, and parse the response.

JavaScript code
async function loadStatus() {
  const response = await fetch('/demo-status.json');
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}
loadStatus().then(console.log).catch(() => console.error('Cannot load demo status'));

Practical useUse a sanitized local fixture for a status prototype.

Common mistakesfetch does not reject on HTTP 404/500. CORS and authentication still apply; do not put secrets in browser code.

Source: developer.mozilla.org documentation

JSON.parse and JSON.stringify

Convert JSON text to a value and format it back into readable text.

JavaScript code
const status = JSON.parse('{"running":true}');
console.log(JSON.stringify(status, null, 2));

Practical useInspect a demo API fixture.

Common mistakesJSON parsing can throw. JSON cannot represent functions or undefined as object values.

Source: developer.mozilla.org documentation

Project structure

Export and import a module

Export a helper from one file and import it from another.

JavaScript code
// labels.js
export const label = name => `Site: ${name}`;

// main.js
import { label } from './labels.js';
console.log(label('Demo'));

Practical useSeparate view helpers in an isolated frontend prototype.

Common mistakesThese are two separate files. In HTML load main.js with type="module" and serve over HTTP rather than file://.

Source: developer.mozilla.org documentation

Back to top ↑