---
name: javascript-for-rails
description: Use when writing, reviewing, or refactoring JavaScript in a Rails or Stimulus app, or whenever the goal is clean, readable, English-like JavaScript. Applies the style principles from "JavaScript for Rails Developers": small public APIs, intentional names, early returns, private getters, readable object APIs, and refactoring procedural code into focused classes.
---

# JavaScript for Rails: Write Code That Reads Like English

## The one rule

Code is read far more often than it is written. Optimize for the next reader, not for the writer. If a line has to be decoded, rename or extract until it reads like a sentence.

The target is JavaScript that a Rubyist can scan and understand:

```javascript
this.collaboration.attach({ to: this.editor })
```

Reads as "collaboration, attach to editor."

## Write as little JavaScript as possible

Before writing any JavaScript, ask whether HTML, Turbo, or CSS already solves it.

- Start with Turbo Drive. Use Turbo Frames for independent page regions. Reach for Turbo Streams only when frames cannot update multiple regions at once.
- Use CSS for simple toggles, dropdowns, tabs, and validation feedback where appropriate.
- Add JavaScript only for behavior that genuinely needs it.
- Prefer server-rendered HTML plus small Stimulus controllers over client-side rendering.

## Naming

Names are the primary documentation. Spend time on them.

- Name methods so the call site reads as a sentence: `panels.with(...)`, `theme.set(...)`, `autocomplete.for(...)`, `splitView.for(...)`, `panelFor[config.type]`.
- Prefer verbs for actions (`attach`, `create`, `pair`, `sync`, `convert`) and nouns for values (`content`, `selection`, `targetLine`).
- Name predicates as questions: `#atBoundary`, `#moveUp`, `#disabled`, `#cannotSync`.
- Derive names from their source so relationships stay obvious: `themeValue` → `validatedThemeValue`.
- Use `#private` for internals, and a `// private` comment to mark the section.
- Never abbreviate to save characters. The reader pays for it.

## Shape of a class

- Keep the public API small: usually one to three public methods.
- Mark internal methods and fields private with `#`. JavaScript privacy is real and enforced; use it.
- Order methods consistently:
  1. Constructor
  2. Public methods
  3. Private methods, ordered by the order in which they are called
  4. Getters
  5. Setters
- The constructor only assigns state. Behavior lives in methods.
- Use getters for computed values, configuration, and validation. Call them without parentheses: `this.extensions`, `this.#validatedThemeValue`.
- Every getter must return something explicitly; otherwise it returns `undefined`.
- Store internal state in private fields: `#pairs`, `#conversions`, `#currencyFormatter`.
- When logic grows past a few lines, or needs shared state, introduce a class instead of more free functions. If it is more than a few lines, it likely wants to be a class.

Example of a well-shaped class:

```javascript
class Line {
  constructor(view, direction, duplicate = false) {
    this.view = view
    this.direction = direction
    this.duplicate = duplicate
  }

  move() {
    if (!this.duplicate && this.#atBoundary) return false

    const operation = this.duplicate ? this.#duplicate() : this.#swap()

    this.view.dispatch(operation)

    return true
  }

  // private

  #duplicate() {
    return { changes: this.#duplicateChanges, selection: this.#newSelection }
  }

  #swap() {
    return { changes: this.#swapChanges, selection: this.#newSelection }
  }

  get #atBoundary() {
    return this.#moveUp
      ? this.#currentLine.number === 1
      : this.#currentLine.number === this.#document.lines
  }
}
```

The public surface is one method. Everything else is a small, named, private step.

## Shape of a method

- Use guard clauses instead of nesting: `if (!this.editor) return`.
- Prefer one-line guards when the body is a single statement: `if (!enabled) return`.
- Return early, return often. Flat code beats indented code.
- Use implicit returns for single expressions: `received: data => this.#sync(data)`.
- Use a block body when you need multiple statements or an explicit `return`.
- Give every method one job. If you need "and" to describe it, split it.
- Extract repeated work (a dispatch, a calculation, a lookup) into one place.
- Pass options as a single object with defaults: `{ duplicate = false } = {}`.
- If a method has fewer than three parameters, inline them; otherwise destructure inside the body.
- Use named option keys to make calls self-explanatory: `attach({ to: editor })`, `createClone({ from: sourceEditor })`, `pair(first, { with: second })`.
- Use arrow functions in callbacks to preserve `this`.
- Use `_` for a parameter you intentionally do not use.

```javascript
create(editor, { enabled }) {
  if (!enabled) return

  const firstEditor = this.#createClone({ from: editor })
  const secondEditor = this.#createClone({ from: editor })

  this.#pair(firstEditor, { with: secondEditor })

  editor.destroy()

  return secondEditor
}
```

Each line states intent. No line requires holding three variables in your head.

## Design APIs that read like English

- Prefer small objects with fluent method names over loose functions.
- Use lookup objects instead of `if`/`else` chains:

```javascript
const panelFor = {
  static: Static
}

export const panels = {
  with: configs => configs.flatMap(config =>
    panelFor[config.type] ? new panelFor[config.type](config).toExtension() : []
  )
}
```

- Use a lookup object with a fallback for variants:

```javascript
const languages = {
  javascript: javascript(),
  html: html(),
  css: css()
}

languages[language] || javascript()
```

- Use the Strategy pattern when cases share a shape but differ in algorithm:

```javascript
#conversions = {
  camel: camelize,
  snake: underscore,
  kebab: dasherize
}

#convertToCase(targetCase) {
  return this.#conversions[targetCase](this.#text)
}
```

- Return `this` for chaining when a class configures something: `new Widget().init().setColor("black")`.
- Keep the external API stable when refactoring. A class can replace a function without changing the call site.
- Always provide an explicit cleanup method, even when it only delegates: `destroy: editor => editor?.destroy()`.

## Data and control flow

- Prefer `const` by default, `let` only when reassigning. Never use `var`.
- Use strict equality `===` unless coercion is intentional.
- Use optional chaining `?.` and nullish coalescing `??` instead of defensive nesting.
- Use `filter(Boolean)` to drop falsy entries from arrays of optional extensions.

```javascript
return [
  enableLineNumbers && lineNumbers(),
  enableFoldGutter && foldGutter(),
  enableActiveLine && highlightActiveLine(),
  enableIndentWithTab ? keymap.of([indentWithTab]) : null
].filter(Boolean)
```

- Use `flatMap` when mapping produces arrays that should be flattened.
- Use `reduce` for accumulation; use `forEach` when a plain loop is clearer.
- Extract magic strings and numbers into named constants (`statuses`, `themes`, `languages`, `panelStyles`).
- Use `Object.keys`, `Object.entries`, `Object.hasOwn`, and `Object.assign` instead of manual iteration or repeated assignment.
- Prefer `textContent` over `innerHTML` for plain text: it is faster and avoids XSS.
- Use template literals for interpolation. Use `join("")` or a template literal to compose chunks of markup.
- Use `async`/`await` over long `.then` chains.

## Modules and files

- One concern per file.
- Co-locate a feature in its own folder: `editor/setups.js`, `editor/autocomplete.js`, `editor/theme.js`, `editor/panels/static.js`.
- Put reusable helpers in a shared helpers file.
- Use named exports by default; default exports only where a framework or package convention requires it.
- Use an `index.js` barrel to re-export a feature's public surface.
- Group imports by origin, with blank lines between groups: framework, third-party packages, local modules, helpers.

```javascript
import { Controller } from "@hotwired/stimulus"

import { EditorView } from "@codemirror/view"
import { standardSetup } from "./editor/setups"
import { autocomplete } from "./editor/autocomplete"

import { debounce } from "./helpers"
```

## Refactoring procedural code

When a function becomes an if/else maze, refactor in this order:

1. Write the naive version first. Get the behavior correct.
2. Extract each branch into its own named method.
3. Remove duplication: pull shared work (dispatch, rendering, calculation) into one place.
4. Name the patterns that emerge.
5. If the result is still hard to scan, introduce a class with one public method.
6. Convert repeated derived values into private getters.
7. Confirm the public API did not change. Re-run the behavior.

The final goal is that the public method reads as a short recipe and the private getters hold the detail.

## Smells and fixes

| Smell | Fix |
| --- | --- |
| Deeply nested `if`/`else` | Guard clauses and early returns |
| A method that needs "and" to describe | Split into focused methods |
| Repeated `view.dispatch(...)` | Build one operation object, dispatch once |
| Repeated `dom.style.x = ...` | `Object.assign(dom.style, styles)` |
| `if`/`else` choosing between algorithms | Lookup object or Strategy pattern |
| Inline magic strings | Named constants |
| Long inline callback logic | Extract a private method and call it |
| Free functions sharing state | Introduce a class with private fields |
| Getter used like a method | Drop the parentheses; define it with `get` |
| Public method count creeping up | Make the extras `#private` |
| Undeclared variable | `const`/`let`; strict mode; `no-undef` lint rule |
| Unused callback parameter | Name it `_` |
| Complex conditional inside a callback | Extract a predicate getter such as `#cannotSync` |

## Stimulus-specific readability

- Keep lifecycle responsibilities separate:
  - `initialize` for non-DOM setup: timers, counters, caches, wrapped callbacks.
  - `connect` for DOM access: listeners, queries, third-party instances.
  - `disconnect` for teardown: remove listeners, destroy instances, clear timers.
- Pair every `connect` action with a `disconnect` action. This prevents memory leaks.
- Use Stimulus values for configuration and targets for DOM updates.
- Name value callbacks exactly `valueNameValueChanged()`.
- Wrap expensive callbacks in `debounce` and create the debounced function in `initialize`.
- Keep controllers thin: delegate real work to dedicated classes and pass only what they need.
- Validate external input through a getter with a safe fallback, e.g. `validatedThemeValue`.

## Final checklist

Before considering JavaScript done, verify:

- Can each public method be read aloud as a sentence?
- Is the public API as small as it can be?
- Are internal methods and fields private with `#`?
- Are methods ordered by call order, with getters last?
- Is every special value named?
- Are conditionals flat, with early returns?
- Could any `if`/`else` become a lookup object?
- Is repeated work extracted into one place?
- Does every setup have a matching teardown?
- Would a Rails developer understand it without extra context?

If the answer to the last question is no, rename or extract until it is yes.
