Code style for JavaScript

snake_case in our own code, camelCase where a host API demands it, const by default, no semicolons.

Status
Draft
Version
0.1
Last updated

Rules and reasons

  • New project code uses snake_case for functions and methods. Where a host API or SDK requires camelCase (the DOM, third-party libraries), use camelCase only in that thin adapter layer and keep the logic in snake_case.
  • const by default, let when a binding changes, no var in new code.
  • No semicolons at the end of statements; rely on automatic semicolon insertion and use it consistently in a package. A statement must then never start a line with an opening parenthesis, bracket or template literal, and tooling should check that.
  • Allman braces for functions, classes and control flow. Object and collection literals keep one readable style per module.
  • try and catch only around I/O, parsing and framework entry points; domain logic returns values.
  • One responsibility per file; named constants instead of magic numbers.

Generator mapping

CanonicalJavaScript
load_url (method)load_url internally, loadUrl in a published npm API
web_view_configuration (type)WebViewConfiguration
minimal_ui (constant)MINIMAL_UI

Example

const COPIED_LABEL_MS = 1800

function show_copied (button)
{
    button.textContent = 'Copied'
    window.setTimeout(() => { button.textContent = 'Copy' }, COPIED_LABEL_MS)
}

Counter-arguments

  • Google's JavaScript guide requires a semicolon at the end of every statement and forbids relying on automatic insertion. It also uses lowerCamelCase for methods and K&R braces. It is a widely used reference style.
  • Without semicolons, a few line starts change the meaning of the previous line. The rule above avoids them, but it is a rule the team has to keep and check.
  • snake_case in JavaScript meets camelCase in every standard library and framework call, so a file can show both.

Sources