Code style.

Our code must be as clear and readable as possible.

It’s actually the art of programming — coding a complex task in a way that is correct and readable by people. A good code style goes a long way toward achieving this.

grammar

Here is a cheat sheet with some suggested rules (see below for details) :

Now, let’s discuss these rules and their reasons in detail.

Note: No rules are “required”

No rule is “written in stone.” These are stylistic preferences, not religious dogma.

Curly braces

In most JavaScript projects, the curly braces are “Egyptian” style. The “Egyptian” style is also known as K&R style – the opening bracket of a code segment is at the end of a line, not the style of another line), and the opening curly bracket is on the same line as the corresponding keyword – rather than a new line. There should also be a space before the opening parenthesis, as follows:

if (condition) {
  // do this
  / /... and that
  / /... and that
}
Copy the code

One-line constructs, such as if (condition) doSomething(), are also an important use case. Should we use curly braces? If so, where?

Here are some notes for each case, so you can judge their readability for yourself:

  1. 😠 Beginners often write like this. Very bad! We don’t need curly braces here:

    if (n < 0) {alert(`Power ${n} is not supported`); }Copy the code
  2. 😠 splits into separate lines without curly braces. Never do this, adding a new line is very error-prone:

    if (n < 0)
      alert(`Power ${n} is not supported`);
    Copy the code
  3. 😏 is written on a single line without curly braces — this is fine if it’s short:

    if (n < 0) alert(`Power ${n} is not supported`);
    Copy the code
  4. 😃 Best way:

    if (n < 0) {
      alert(`Power ${n} is not supported`);
    }
    Copy the code

For very short code, a single line is acceptable: for example, if (cond) return NULL. But code blocks (the last example) are usually more readable.

The length of the line

No one likes to read a long list of code, so it’s best to break it up.

Such as:

// The callback sign 'allows the string to be split into multiple lines
let str = ` Ecma International's TC39 is a group of JavaScript developers, implementers, academics, and more, collaborating with the community to maintain and evolve the definition of JavaScript. `;
Copy the code

For the if statement:

if (
  id === 123 &&
  moonPhase === 'Waning Gibbous' &&
  zodiacSign === 'Libra'
) {
  letTheSorceryBegin();
}
Copy the code

The maximum length of a line of code should be agreed upon at the team level. Usually 80 or 120 characters.

The indentation

There are two types of indentation:

  • Horizontal indentation: 2 or 4 Spaces.

    A horizontal indentation usually consists of two or four Spaces or “Tab” characters. Choosing which way to go is an old holy war. Spaces are a little more common these days.

    One of the advantages of choosing Spaces over tabs is that it allows you to make indentation configurations more flexible than the “Tab” character.

    For example, we could align the argument with the opening parenthesis as follows:

    show(parameters,
         aligned, // There are 5 Spaces to the left
         one,
         after,
         another
      ) {
      // ...
    }
    Copy the code
  • Vertical indentation: Blank lines used to break code into logical blocks.

    Even a single function is usually divided into several logical blocks. In the following example, the initialized variable, the main loop structure, and the return value are all split vertically:

    function pow(x, n) {
      let result = 1;
      // <--
      for (let i = 0; i < n; i++) {
        result *= x;
      }
      // <--
      return result;
    }
    Copy the code

    Inserting an extra blank line helps make the code more readable. When writing code, you should not have more than nine lines in a row that are not vertically split.

A semicolon

Each statement should be followed by a semicolon. Even though it can be skipped.

Semicolons are indeed optional in some programming languages, and they are rarely used in those languages. But in JavaScript, the code is prone to errors in the rare cases where newlines are sometimes not interpreted as semicolons. See the code Structure chapter for more information.

If you are an experienced JavaScript programmer, you can opt for a non-semicolon code style like StandardJS. Otherwise, it’s best to use semicolons to avoid potential pitfalls. Most developers should use semicolons.

Nested hierarchies

Try not to nest code too deeply.

For example, in loops, it is sometimes a good idea to use the continue directive to avoid additional nesting.

For example, nested if conditions should not be added as follows:

for (let i = 0; i < 10; i++) {
  if (cond) {
    ... // <- another layer of nesting}}Copy the code

We can write this:

for (let i = 0; i < 10; i++) {
  if(! cond)continue; .// <- no additional nesting
}
Copy the code

Similar things can be done with if/else and return.

For example, the following two structures are the same.

The first:

function pow(x, n) {
  if (n < 0) {
    alert("Negative 'n' not supported");
  } else {
    let result = 1;

    for (let i = 0; i < n; i++) {
      result *= x;
    }

    returnresult; }}Copy the code

The second:

function pow(x, n) {
  if (n < 0) {
    alert("Negative 'n' not supported");
    return;
  }

  let result = 1;

  for (let i = 0; i < n; i++) {
    result *= x;
  }

  return result;
}
Copy the code

But the second is more readable, because the “special case” of n < 0 is handled at the beginning. Once the condition is checked, code execution can move into the “main” code flow without additional nesting.

Function of position

If you are writing several “helper classes” of functions and some code that uses them, there are three ways to organize these functions.

  1. Declare these functions above the code that calls them:

    // Function declaration
    function createElement() {... }function setHandler(elem) {... }function walkAround() {... }// The code that calls the function
    let elem = createElement();
    setHandler(elem);
    walkAround();
    Copy the code
  2. Write the calling code first, then the function

    // The code that calls the function
    let elem = createElement();
    setHandler(elem);
    walkAround();
    
    // -- auxiliary class functions --
    function createElement() {... }function setHandler(elem) {... }function walkAround() {... }Copy the code
  3. Blending: Declare a function the first time it is used.

In most cases, the second option is better.

That’s because when we read code, the first thing we want to know is “what does it do?” If the code goes first, this information is displayed at the beginning of the entire program. After that, we probably don’t need to read about these functions, especially if their names clearly show what they do.

Style guide

The style guide contains general rules for “if you write” code, such as which quotes to use, how many Spaces to indent, the maximum length of a line of code, and many more details.

When all members of the team use the same style guide, the code will look uniform. No matter who on the team wrote it, it was the same style.

Sure, a team can create their own style guide, but there’s no need to do that. There are plenty of well-written code style guides to choose from.

Some popular options:

  • Google JavaScript Style Guide
  • Airbnb JavaScript Style Guide
  • Idiomatic.JS
  • StandardJS
  • There are many more…

If you are a beginner, you can start with the above in this chapter. Then you can browse through other style guides and choose the one you like best.

Automatic checker

Linters are tools that can automatically check code styles and suggest improvements.

The beauty of them is that when you do a code style check, you can also find code errors, such as typos in variable or function names. So even if you don’t want to stick to a particular code style, I recommend installing a checker.

Here are some of the best known code review tools:

  • JSLint – One of the first checkers.
  • JSHint – More Settings than JSLint.
  • ESLint – Should be the latest one.

They all do a good job of checking code. I’m using ESLint.

Most inspectors can be integrated with the editor: simply enable the plug-in and configure the code style in the editor.

For example, to use ESLint you would do something like this:

  1. Installation Node. JS.
  2. usenpm install -g eslintThe NPM command (which is a JavaScript package installer) installs ESLint.
  3. Create a name in the root directory of your JavaScript project (the folder that contains all the files for the project).eslintrcConfiguration file.
  4. Install/enable plug-ins in an editor that integrates with ESLint. Most editors have this option.

Here is an example of an.eslintrc file:

{
  "extends": "eslint:recommended"."env": {
    "browser": true."node": true."es6": true
  },
  "rules": {
    "no-console": 0."indent": ["warning".2]}}Copy the code

The “extends” directive here means that we are setting based on a setting item “ESLint :recommended”. After that, we make our own rules.

You can also download style rule sets from the Web and extend them. For more details on installation, see eslint.org/docs/user-g…

In addition, some ides have built-in inspectors, which are convenient but not as customizable as ESLint.

conclusion

All of the syntax rules described in this chapter (and mentioned in the code Style guide) are designed to help you improve the readability of your code. They are all debatable.

When thinking about how to write “better” code, the question we should ask ourselves is, “What makes code more readable and understandable?” “And” What can help us avoid mistakes? These are the main principles to keep in mind when discussing and choosing code styles.

Read the popular code style guide to help you keep up with the latest ideas on changing code style trends and best practices.

Homework assignments

Do the questions yourself and then look at the answers.

Bad code style

Degree of importance: ⭐️⭐️ ️⭐

What’s wrong with the following code style?

function pow(x,n)
{
  let result=1;
  for(let i=0; i<n; i++) {result*=x; }return result;
}

let x=prompt("x?".' '), n=prompt("n?".' ')
if (n<=0)
{
  alert(`Power ${n} is not supported, please enter an integer number greater than zero`);
}
else
{
  alert(pow(x,n))
}
Copy the code

Repair it.

The answer:

Reply 1-3-2 in the background of wechat public account “Technology Talk” to obtain the answer to this question.


Modern JavaScript Tutorials: Open source modern JavaScript tutorials from beginner to advanced quality. React provides a JavaScript tutorial for MDN learners.

Read for free online: zh.javascript.info


Scan the QR code below and follow the wechat public account “Technology Chat” to subscribe for more exciting content.