Skip to content

JavaScript Implementation Standards ​

Rules for JavaScript that is maintainable, fast, secure and accessible. Each rule states its strength (MUST / MUST NOT / SHOULD) at the end of its summary, and each section lists rules from strongest to weakest.

Check for a Built-in Feature First ​

Before writing a script, check whether an HTML element or CSS can do the same job. Built-in features mean less code, better performance, and keyboard and screen reader support from the start.

Built-in features to use first
What you needBuilt-in featureWhy use it
Panel / accordion toggle<details> / <summary>Keyboard and assistive technology support with no script
Modal dialog<dialog> + showModal()Focus containment and Escape to close come built in
Smooth scrollingscroll-behavior: smoothOne line of CSS
Element that follows scrollingposition: stickyNo scroll listener to run
Lazy-loaded imagesloading="lazy" attributeThe browser schedules loading optimally
Basic input validationrequired, type, pattern, :user-invalidBrowser-native error messages
Tabs / carouselsRevisit the designAccessibility is costly to get right, so confirm they are really needed first
Do not build in JavaScript what HTML or CSS already does SHOULDCD-R12
Use the built-in features in the table above. Custom versions add maintenance work and room for defects.
Check: CD-12

Basics ​

Compare with === / !==, never == / != MUSTCD-R13
== coerces types, so unintended values compare as equal.
Check: CD-13
Return early when the target element is missing MUSTCD-R14
Check at the top of each function so the script does not fail on pages without the element, or when it is loaded twice.
Check: CD-14
Do not create global variables MUST NOTCD-R15
Even where ES modules cannot be used (build constraints, inline scripts), keep variables out of the global scope.
Check: CD-15
Do not use var MUST NOTCD-R16
Declare with const or let.
Check: CD-16
No jQuery or other legacy libraries in new projects MUST NOTCD-R17
Do not add a large library for something plain JavaScript does in a few dozen lines, either.
Check: CD-17
Load scripts with <script type="module"> SHOULDCD-R18
Modules keep the global scope clean, need no IIFE wrapper, and run after HTML parsing, like defer.
Check: CD-18
Declare variables that are never reassigned with const SHOULDCD-R19
Use let only for variables that must be reassigned.
Check: CD-19

Returning early when the element is missing:

javascript
const trigger = document.querySelector('[data-accordion-trigger]')
if (!trigger) {
  return
}

Files and Modules ​

text
assets/js/
├── main.js            # Entry point: initializes the modules on the page
└── modules/
    ├── accordion.js
    └── form-validation.js
Select elements by data-* attributes MUSTCD-R20
Do not use styling classes as selectors, so design changes do not break scripts.
Check: CD-03
One module, one feature SHOULDCD-R21
Export an initialization function that takes the component's root element as its argument.
Check: CD-20
Show and hide with hidden or a state attribute SHOULDCD-R22
Use the hidden attribute or data-state instead of setting element.style.display, so presentation stays in CSS.
Check: CD-21

A module:

javascript
// modules/accordion.js
export function initAccordion(root) {
  const trigger = root.querySelector('[data-accordion-trigger]')
  const panel = root.querySelector('[data-accordion-panel]')

  if (!trigger || !panel) {
    return
  }

  trigger.addEventListener('click', () => {
    const isExpanded = trigger.getAttribute('aria-expanded') === 'true'
    trigger.setAttribute('aria-expanded', String(!isExpanded))
    panel.hidden = isExpanded
  })
}
javascript
// main.js
import { initAccordion } from './modules/accordion.js'

document.querySelectorAll('[data-accordion]').forEach(initAccordion)

Toggling visibility:

javascript
// Incorrect: inline styles get in the way of CSS control and animation
element.style.display = 'none'

// Correct: the hidden attribute works together with CSS
element.hidden = true

Accessibility ​

A custom component is done only when keyboard operation, focus management and ARIA states all work MUSTCD-R23
See the Custom UI Guidelines for specifications and patterns.
Check: CD-22

Performance ​

Throttle scroll and resize handlers MUSTCD-R24
Use debounce or throttle so heavy work does not run on every event.
Check: CD-23
Remove listeners added to window or document MUSTCD-R25
Call removeEventListener on SPA navigation or when a component is destroyed, to prevent memory leaks.
Check: CD-24
No render-blocking scripts in <head> MUST NOTCD-R26
Use type="module" or defer so scripts run after HTML parsing.
Check: CD-25
Watch position and size with IntersectionObserver / ResizeObserver SHOULDCD-R27
Lighter and more accurate than calculating positions from scroll offsets.
Check: CD-26
Batch DOM reads before writes SHOULDCD-R28
Do not alternate reads such as offsetWidth or getBoundingClientRect() with style changes; each switch forces the browser to recalculate layout.
Check: CD-27

Error Handling and Security ​

Wrap fetch in try...catch and tell users when it fails MUSTCD-R29
On network or HTTP errors, show on screen what went wrong.
Check: CD-28
Insert untrusted data with textContent MUSTCD-R30
Never put user input or external data into innerHTML. When HTML must be inserted, sanitize it first. Unsanitized, it lets malicious scripts run (XSS).
Check: CD-29
No API secret keys or auth tokens in code MUST NOTCD-R31
Anyone can read built JavaScript.
Check: CD-30

Preventing XSS:

javascript
// Incorrect: parsed as HTML, so a malicious script can run (XSS)
container.innerHTML = userInputComment

// Correct: inserted as plain text
container.textContent = userInputComment

What Not to Use ​

No document.write(), eval() or HTML on* attributes MUST NOTCD-R32
They create security holes and conflict with Content Security Policy (CSP).
Check: CD-31
No alert(), confirm() or prompt() in deliverables MUST NOTCD-R33
They block interaction, and their look and wording cannot be adjusted.
Check: CD-32
No branching on the User-Agent string MUST NOTCD-R34
Test for the feature itself (feature detection). User-Agent checks break as browsers update.
Check: CD-33
No console.log() or debugger left in production code MUST NOTCD-R35
They add noise to users' consoles, and debugger halts anyone with developer tools open.
Check: PRF-03PRF-03 Leftover debug code✕ NGconsole.log left inThe production bundle still contains console.log and debugger✓ OKNo debug codeThe production bundle has no console.log or debuggerStripped from production, CD-34