Javascript beautiful coding style

Lecture



The code should be as readable and understandable. This requires a good style of writing code. In this chapter, we will look at the components of this style.

Syntax

Cheat sheet with the rules of syntax (details of their options are discussed below):

  Javascript beautiful coding style

Not everything is straightforward here, so let's sort these rules in more detail.

Braces

Written on the same line, the so-called "Egyptian" style. Before the bracket - a space.

  Javascript beautiful coding style

If you already have experience in development, and you are used to making brackets on a separate line - this is also an option. In the end, you decide. But in most JavaScript frameworks, this is exactly the style.

If the condition and the code are short enough, for example if (cond) return null , then writing in one line is quite readable ... But, as a rule, a separate line is still perceived better.

Line length

The maximum length of the string is agreed in the command. As a rule, it is either 80 or 120 characters, depending on what monitors the developers have.

Longer lines must be broken to improve readability.

Indentation

Indenting need two types:

  • Horizontal indent, with nesting - two (or four) spaces.

    As a rule, spaces are used because they allow you to make more flexible "configuration indentation" than the symbol "Tab".

    For example, align the arguments with respect to the opening bracket:

     show("Строки" + " выровнены" + " строго" + " одна под другой"); 
  • Vertical indent, for better breakdown of the code - line feed.

    Used to separate logical blocks within a single function. In the example, the initialization of the variables, the main loop and the return of the result are separated:

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

    Insert an extra line feed where it makes the code more readable. There should not be more than 9 lines of code in a row without vertical indent.

Semicolon

Semicolons should be set, even if they seem to be missing.

There are languages ​​in which the semicolon is optional, and nobody puts it there. In JavaScript, the newline replaces it, but only partially, so it’s better to put it, as discussed earlier.

Naming

General rule:

  • The variable name is a noun.
  • The function name is a verb or begins with a verb. It happens that the names for short make nouns, but the verbs are clearer.

For names, English is used (not translit) and camel notation.

For more details, read about function names and variable names.

Nesting levels

There should be few nesting levels.

For example, checks in cycles can be done through “continue” so that there is no additional level if(..) { ... } :

Instead:

 for (var i = 0; i < 10; i++) { if (i подходит) { ... // <- уровень вложенности 2 } } 

Use:

             for (var i = 0; i < 10; i++) { if (i не подходит) continue; ... // <- уровень вложенности 1 } 

The situation is similar with if/else and return . The following two designs are identical.

First:

 


 function isEven(n) { // проверка чётности if (n % 2 == 0) { return true; } else { return false; } } 

Second:

 
 function isEven(n) { // проверка чётности if (n % 2 == 0) { return true; } return false; } 

If there is a return in the if block, then the else is not needed.

It is better to quickly handle simple cases, return the result, and then deal with the complex, without an additional level of nesting.

In the case of the isEven function, it would be easier to proceed:

 function isEven(n) { // проверка чётности return !(n % 2); } 

... However, if the code !(n % 2) less obvious to you than the previous version, then you should use the previous one.

The main thing for us is not the brevity of the code, but its simplicity and readability. Shorter code is not always easier to understand than a more extensive one.

Functions = Comments

Functions should be small. If the function is large - it is desirable to break it into several.

This rule is difficult to follow, but worth it. What is the comment here?

Calling a separate small function is not only easier to debug and test - the fact of its presence is an excellent comment .

Compare, for example, the two showPrimes(n) functions to display primes up to n .

The first option uses the label:

 function showPrimes(n) { nextPrime: for (var i = 2; i < n; i++) { for (var j = 2; j < i; j++) { if (i % j == 0) continue nextPrime; } alert( i ); // простое } } 

The second option is the additional isPrime(n) function to test for simplicity:

                            function showPrimes(n) { for (var i = 2; i < n; i++) { if (!isPrime(i)) continue; alert(i); // простое } } function isPrime(n) { for (var i = 2; i < n; i++) { if ( n % i == 0) return false; } return true; } 

The second option is simpler and clearer, isn't it? Instead of a piece of code, we see a description of the action that takes place there (check isPrime ).

Functions - under code

There are two ways to arrange the functions necessary to execute code.

  1. Functions on the code that uses them:

                                                // объявить функции function createElement() { ... } function setHandler(elem) { ... } function walkAround() { ... } // код, использующий функции var elem = createElement(); setHandler(elem); walkAround(); 
  2. First the code, and the functions below:

                                       // код, использующий функции var elem = createElement(); setHandler(elem); walkAround(); // --- функции --- function createElement() { ... } function setHandler(elem) { ... } function walkAround() { ... } 

... In fact, there is still a third "style" in which the functions are randomly scattered around the code, but this is not our method, is it?

As a rule, it is better to allocate functions under the code that uses them.

That is, the 2nd method is preferred.

The fact is that when reading such a code, we want to know first of all what it does , and only then what functions help it. If the code goes first, then it just gives the necessary information. As for the functions, it is quite possible that we will not need to read them, especially if they are adequately named and what they do is clear from the name.

Bad comments

The code needs comments.

I'll start right away with almost no comments.

There should be a minimum of comments that answer the question “what happens in the code?”

Interestingly, in the code of novice developers, there are usually no comments, or they are just of this type: “what is done in these lines”.

Seriously, good code is clear.

R. Martin remarkably expressed this in his book “Clean Code”: “If it seems to you that you need to add a comment to improve understanding, it means that your code is not simple enough, and maybe you should rewrite it”.

If you have formed a long “sheet”, then it may be worth splitting it into separate functions, and then from their names it will be clear what this or that fragment does.

Yes, of course, there are complex algorithms, tricky solutions for optimization, so you can’t just ban such comments. But before you write like this - think: “Is it possible to make the code clear without them?”

Good comments

And what comments are helpful and welcome?

  • The architectural commentary is “how it is, in general, arranged.”

    What components are there, what technologies are used, interaction flow. What and why this script. A bird's-eye view. These comments are especially needed if you are not one, but a big project.

    For the description of the architecture, by the way, a special language UML was created, beautiful diagrams, but it is possible without it. The main thing is to be understood.

  • Reference comment before the function - about what exactly it does, what parameters it takes and what it returns.

    For such comments, there is a JSDoc syntax.

     /** * Возвращает x в степени n, только для натуральных n * * @param {number} x Число для возведения в степень. * @param {number} n Показатель степени, натуральное число. * @return {number} x в степени n. */ function pow(x, n) { ... } 

    Such comments allow you to immediately understand what the function accepts and does, without delving into the code.

    By the way, they are automatically processed by many editors, such as Aptana and JetBrains editors, who take them into account when autocompleting, and also output them in auto-help when typing code.

    In addition, there are tools, such as JSDoc 3, that can generate HTML-based documentation from such comments. More information about this can also be found at http://usejsdoc.org/.

... But much more important may be comments that explain not what , and why exactly this happens in the code!

As a rule, it is possible to understand from the code what it does. Of course, everything happens, but in the end, you see this code. However, much more important may be what you do not see !

Why is this done that way? To this the response code itself does not give.

For example:

There are several ways to solve the problem. Why was this one chosen?

For example, you tried to solve the problem differently, but it did not work out - write about it. Why did you choose this particular solution? This is especially important in cases when not the first method that comes to mind, but some other one is used.

Without this, for example, this situation is possible:

  • You open the code that was written some time ago, and you see that it is “non-optimal”.

  • You think: "What a fool I was," and rewrite under the "more obvious and correct" option.

  • ... The rush, of course, is good, but only this option you have already thought about before. And they refused, and why - they forgot. In the process of rewriting, they remembered, of course (fortunately), but the result was a loss of time to re-think.

    Comments that explain the choice of solution are very important. They help to understand what is happening and take the right steps in developing the code.

What non-obvious features does this code provide? Where else are they used?
In a good code should be at least unobvious. But where it is - please comment.
Comments are important

One of the indicators of a good developer is the quality of comments, which allow you to effectively maintain the code, return to it after any pause, and easily make changes.

Style guides

When a whole team is involved in writing a project, there should be one code standard describing where and when to put spaces, commas, line breaks, etc.

Now, when there are so many finished projects, it makes no sense to invent your entire style guide. You can take already ready, and to which, if desired, you can always add something.

Most are in English, let me know if you find a good translation:

  • Google JavaScript Style Guide
  • JQuery Core Style Guidelines
  • Airbnb javascript style guide
  • Idiomatic.JS (there is a translation)
  • Dojo Style Guide

In order to begin development, the elements of styles indicated in this chapter will suffice. In the future, having seen these guidelines, you can develop your own style, but it is better not to make it particularly “unique and unique”, it will be more expensive for yourself then to work with people.

Automated Check Tools

There are tools that check the style of the code.

The most famous are:

  • JSLint - checks the code for compliance with the JSLint style, in the online interface, you can enter the code at the top, and various test settings at the bottom to make it softer.
  • JSHint is a variant of JSLint with a large number of settings.
  • Closure Linter - check for compliance with the Google JavaScript Style Guide.

In particular, JSLint and JSHint are integrated with most editors, they flexibly adjust to the desired style and completely unnoticeably improve the design, suggesting where and what to fix.

A side effect is that they see some errors, for example undeclared variables. In my case, this is usually the result of typos, which are thus immediately caught. I highly recommend putting something out of it. I am using JSHint.

Total

The described principles of code design are relevant in most projects. There are other useful conventions.

Following (or not following) them, it is necessary to remember that any style tips are good only when they make the code more readable, understandable, easier to maintain.

if you are using the jQuery library, then it is more convenient to listen to the listeners in the following form

var toogleFaq = (function () {


};
var toggleRow = function () {

($ (this) .hasClass ("obggfhg"))
....

};

 

var events = function () {
$ (". awytfyt"). on ("click", toggleRow);
$ (". avyugtue"). on ("click", togglePart);
};

var init = function () {
events ();
};

return {
init: init
};

}) ();

$ (function () {
functq.init ();
});


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone