Writing Maintainable JavaScript (1) -- Basic Formatting

Posted by Calahan on Wed, 26 Jun 2019 22:20:28 +0200

Programs are meant to be read by humans and only incidentally for computers to execute.

Programs are written for people to read, but occasionally let the computer execute them.

Style guideline: Code planning in specification document

Code convention: programming best practices, file and directory planning and annotations

Line feed

When a line reaches the maximum number of characters per line, it needs to be split into two lines manually. Usually, we wrap lines after the operator, and the next line will be indented by two levels (two Tab tabs).

// Recommendation: Wrap lines after operators (comma here), and add two indentations (two Tab tabs) to the second line.
callAFunction(document, element, "some string value", true, 123,
        navigator;)

Statement line breaks can also apply this rule:

if (isLeapYear && isFebruary && day == 29 && itsYourBirthday &&
        noPlans) {
    waitAnotherFourYears();         
}

// The main part of if is still an indentation

Variable wrapping

var result = something + anotherThing + yetAnotherThing +
            anotherSomethingElse;
// When assigning a variable, the position of the second line should be aligned with that of the assignment operator.

Blank line

Separate code with blank lines to ensure that semantically related code is presented together.

  • Between methods;
  • Between the local variable of the method and the first statement;
  • Before multi-line or single-line comments;
  • Insert blank lines between logical fragments of the method to improve readability.
if (wl && wl.length) {

  for (i = 0, l = wl.length; i < 1; ++i) {
    p = wl[i];
    type = Y.Lang.type(r[p]);

    if (s.hasOwnProperty(p) {

        if (merge && type == 'object') {
          Y.mix(r[p], s[p]);
        } else if (ov || !(p in r)) {
          r[p] = s[p];
        }

    }
  }
}

Variables and functions

Naming is not only a science, but also a technology. Following the naming of humps, name the data type; for example, name count, length and size indicate that the data type is a number, while name, title and message indicate that the data type is a string; function name prefix should be a verb.

verb Meaning
can Function returns a Boolean value
has Function returns a Boolean value
is Function returns a Boolean value
get Function returns a f non-Boolean value
set Function to save a value
 if (isEnabled()) {
   setName("nicholas");
 }

 if (getName() === "Nicholas") {
   doSomething();
 }

constant

Name with uppercase letters and underscores to separate words

var MAX_COUNT = 10;
var URL = "http://www.nczonline.net/";

Constructor

Constructor naming is often a noun, used to create an instance of a certain type, usually using the big hump naming method, often used with new before.

function Person(name) {
    this.name = name;
}

Person.prototype.sayName = function() {
    alert(this.name);
};

var me = new Person("Nicholas");

Character string

Strings can be enclosed in double or single quotes.

Difference: Strings in double quotes need to be escaped, strings in single quotes need not be escaped.

// Legitimate JavaScript code
var name = "Nicholoas says, \"Hi.\"";

// Legal JS code
var name = 'Nicholos says, "Hi"';

// Multi-line strings recommend "+" to divide strings into multiple parts
var longString = "Here's the story, of a man " +
                "named Brady.";

Object Direct Quantity

Write all attributes directly when creating an object

// Recommendation
var book = {
    title: "Maintainable JavaScript",
    author: "Nicholas C. Zakas"
};

// not Recommended
var book = new Object();
book.title = "Maintainable JavaScript";
book.author = "Nicholas C. Zakas";

Array direct quantity

// Good
var colors = ["red", "blue", "white"];
var numbers = [1, 2, 3, 4];

// Bad
var colors = new Array("red", "blue", "white");
var numbers = new Array(1, 2, 3, 4);

Topics: Javascript Programming