Master Clean JavaScript: Coding Style, Variables, Error Handling, and Design Patterns
This article provides a comprehensive guide to writing maintainable JavaScript, covering coding conventions, variable best practices, error handling techniques, object creation methods, prototype and module patterns, and practical examples to help developers build clean, modular, and loosely‑coupled code.
1 Coding Style
Good coding conventions improve readability, maintainability, and team efficiency. Use four spaces for indentation (or tabs if preferred), keep a single space after opening brackets, before colons, around operators, and after anonymous function expressions. Separate unrelated code blocks with blank lines, such as between methods, local variables and the first statement, and before comments.
Indent with four spaces.
Use a single space after opening parentheses and before closing ones.
Place a space around operators.
Separate logical sections with blank lines.
2 Variables
Avoid implicit global variables; any variable declared without var, let, or const becomes a property of the global object. Example:
function obj() {
name = "aotu"; // implicit global
return name;
}Chained assignments also create hidden globals:
function person() {
var a = b = 1; // b is global
}Declare variables at the top of functions to avoid hoisting surprises and use a single‑var pattern for readability:
var a = 1,
b = 1,
c = 1;Minimize global variables; if needed, use a single global namespace (e.g., window.$ and window.jQuery).
3 UI Loose Coupling
Loose coupling means changing one component does not affect others. Recommendations:
Separate JavaScript from CSS; avoid CSS expressions.
Manipulate CSS via class names, not inline styles.
Keep JavaScript out of HTML; place scripts in external files.
Generate HTML with templates or frameworks like Vue or React instead of string concatenation.
4 Error Handling
Throw errors when a predictable problem occurs, and catch them where recovery is possible. Use try…catch blocks:
try {
someMethod();
} catch (ex) {
catchError(ex);
}Optionally add a finally block for cleanup. When you can identify the error condition, use throw new Error("message") or throw a custom object:
throw { name: "myErrorType", message: "arguments must be a DOM element", errorMethod };5 Creating Objects
5.1 Object Literals
Define objects with key‑value pairs for concise, readable code:
var obj = {
name: "aotu",
job: "farmer",
getName: function () { return this.name; }
};
obj.getName();Private members can be simulated with an IIFE (module pattern):
var obj = (function () {
var name = "aotu", job = "farmer";
return {
getName: function () { return name; }
};
})();5.2 Constructor Functions
Basic constructor example:
function Obj() {
this.name = "aotu";
this.job = "farmer";
this.getName = function () { console.log(this.name); };
}
var obj = new Obj();
obj.getName();Force usage of new inside the constructor to avoid accidental global binding:
function Obj() {
if (!(this instanceof Obj)) {
return new Obj();
}
this.name = "aotu";
this.age = 25;
this.getName = function () { console.log(this.name); };
}5.3 Prototype Pattern
Share methods via the prototype to save memory:
function Obj() {}
Obj.prototype.name = "aotu";
Obj.prototype.age = 25;
Obj.prototype.getName = function () { console.log(this.name); };
var o1 = new Obj();
var o2 = new Obj();
console.log(o1.getName === o2.getName); // trueWhen overwriting the entire prototype, remember to reset the constructor reference.
5.4 Module Pattern
Encapsulate private state and expose a public API:
var testModule = (function () {
var testNode = document.getElementById("test");
function privateMethod() { console.log("Private method!"); }
return {
setHtml: function (txt) { testNode.innerHTML = txt; }
};
})();
testModule.setHtml("Hello");The pattern can be combined with a global namespace to avoid polluting the global scope.
6 References
Books: "Writing Maintainable JavaScript" by Nicholas C. Zakas, "JavaScript Design Patterns" by Addy Osmani, "Professional JavaScript for Web Developers" (3rd ed.). Blog series: "Deep Dive into JavaScript".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Aotu Lab
Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.
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.
