Writing Maintainable JavaScript: Principles, Coding Standards, and Best Practices
This article explains why maintainable JavaScript is essential for modern web applications and provides concrete guidelines on coding standards, readability, naming, type transparency, loose coupling, and coding conventions such as respecting object ownership, avoiding globals, and using constants.
In early websites JavaScript was used only for small effects or form validation, but modern web applications consist of thousands of lines of JavaScript that must be maintainable; developers need to treat JavaScript engineering like any other software discipline.
1. What Is Maintainable Code
Maintainable code is easy to understand, follows common sense, adapts to data changes, extends cleanly, and debugs quickly. These traits distinguish a weekend hobbyist from a professional developer.
2. Coding Standards
2.1 Readability
Consistent indentation (typically four spaces) and thorough comments for functions, large code blocks, complex algorithms, and browser‑specific tricks improve readability.
2.2 Variable and Function Naming
Use noun‑like variable names (e.g., car , person ) and verb‑like function names (e.g., getName() , isEnabled() ). Apply camelCase for variables and functions, PascalCase for classes, and UPPER_SNAKE_CASE for constants.
2.3 Variable Type Transparency
Three common ways to indicate a variable’s type are shown below.
// Indicate type by initialization let found = false; // Boolean let count = -1; // number let name = ""; // string let person = null; // object
// Hungarian notation (less readable) let bFound; // Boolean let iCount; // integer let sName; // string let oPerson; // object
// Type annotation comment let found /*:Boolean*/ = false; let count /*:int*/ = 10; let name /*:String*/ = "Nicholas"; let person /*:Object*/ = null;
Be aware that type‑annotation comments can interfere with multi‑line comments.
3. Loose Coupling
3.1 Decoupling HTML/JavaScript
Embedding scripts directly in HTML or using inline event attributes creates strong coupling.
Instead, load JavaScript from external files and attach behavior via the DOM.
3.2 Decoupling CSS/JavaScript
Modifying styles directly in JavaScript tightly couples presentation to behavior.
// Direct style manipulation (tight coupling) element.style.color = "red"; element.style.backgroundColor = "blue";
Prefer changing CSS class names:
// Loose coupling via className element.className = "edit";
3.3 Decoupling Application Logic / Event Handlers
Separate pure application logic from event handling.
// Event handler with embedded logic function handleKeyPress(event) { if (event.keyCode == 13) { let target = event.target; let value = 5 * parseInt(target.value); if (value > 10) { document.getElementById("error-msg").style.display = "block"; } } }
Refactor to:
function validateValue(value) { value = 5 * parseInt(value); if (value > 10) { document.getElementById("error-msg").style.display = "block"; } } function handleKeyPress(event) { if (event.keyCode == 13) { let target = event.target; validateValue(target.value); } }
4. Coding Conventions
4.1 Respect Object Ownership
Never modify objects you do not own (e.g., built‑in prototypes, third‑party libraries). Instead, create new objects or subclasses.
4.2 Avoid Declaring Global Variables
Wrap related code in a single namespace object.
// Bad: two globals var name = "Nicholas"; function sayName() { console.log(name); } // Good: one global namespace var MyApplication = { name: "Nicholas", sayName: function () { console.log(this.name); } };
Large projects often use a top‑level namespace (e.g., Wrox.ProJS ) to avoid collisions.
4.3 Avoid Comparing to null
Prefer explicit type checks (e.g., instanceof Array or typeof ) over generic != null checks.
// Bad null comparison function sortArray(values) { if (values != null) { values.sort(comparator); } } // Recommended function sortArray(values) { if (values instanceof Array) { values.sort(comparator); } }
4.4 Use Constants
Extract repeated literals, UI strings, URLs, and any value that may change into named constants to improve maintainability and support internationalization.
This article is excerpted from the forthcoming "Professional JavaScript (4th Edition)" and is reproduced with permission.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.