Google JavaScript Style Guide Summary
This document summarizes key rules and best practices from the Google JavaScript Style Guide.
1. Source File Basics
- File Naming: All lowercase, with underscores (
_) or dashes (-). Extension must be.js. - File Encoding: UTF-8.
- Whitespace: Use only ASCII horizontal spaces (0x20). Tabs are forbidden for indentation.
2. Source File Structure
- New files should be ES modules (
import/export). - Exports: Use named exports (
export {MyClass};). Do not use default exports. - Imports: Do not use line-wrapped imports. The
.jsextension in import paths is mandatory.
3. Formatting
- Braces: Required for all control structures (
if,for,while, etc.), even single-line blocks. Use K&R style ("Egyptian brackets"). - Indentation: +2 spaces for each new block.
- Semicolons: Every statement must be terminated with a semicolon.
- Column Limit: 80 characters.
- Line-wrapping: Indent continuation lines at least +4 spaces.
- Whitespace: Use single blank lines between methods. No trailing whitespace.
4. Language Features
- Variable Declarations: Use
constby default,letif reassignment is needed.varis forbidden. - Array Literals: Use trailing commas. Do not use the
Arrayconstructor. - Object Literals: Use trailing commas and shorthand properties. Do not use the
Objectconstructor. - Classes: Do not use JavaScript getter/setter properties (
get name()). Provide ordinary methods instead. - Functions: Prefer arrow functions for nested functions to preserve
thiscontext. - String Literals: Use single quotes (
'). Use template literals (`) for multi-line strings or complex interpolation. - Control Structures: Prefer
for-ofloops.for-inloops should only be used on dict-style objects. this: Only usethisin class constructors, methods, or in arrow functions defined within them.- Equality Checks: Always use identity operators (
===/!==).
5. Disallowed Features
withkeyword.eval()orFunction(...string).- Automatic Semicolon Insertion.
- Modifying builtin objects (
Array.prototype.foo = ...).
6. Naming
- Classes:
UpperCamelCase. - Methods & Functions:
lowerCamelCase. - Constants:
CONSTANT_CASE(all uppercase with underscores). - Non-constant Fields & Variables:
lowerCamelCase.
7. JSDoc
- JSDoc is used on all classes, fields, and methods.
- Use
@param,@return,@override,@deprecated. - Type annotations are enclosed in braces (e.g.,
/** @param {string} userName */).
Source: Google JavaScript Style Guide