Уроки Javascript

Javascript Code Agreement – The Media Image

Writer: Valery Sestov Publication date: 01/23/2014

This can be a set of conventions and rules that have to be adopted when writing JavaScript code. At the heart of this settlement are paperwork from Sun, for the Java programming language. However since JavaScript is just not Java, the document has been redesigned relative to the JavaScript language.

The long-term value of the software program is immediately related to the quality of the code. Throughout its existence, the program passes via a huge variety of palms and eyes of builders. If this system code is written in such a means that it could possibly clearly convey its construction and traits, then the chance of breaking it decreases if it is introduced into edits by different developers or by the writer after an extended time period.

Software code agreements might help to improve the standard of the output, and scale back the probability of its failure.

Javascript information

JavaScript packages have to be stored in .js information.

JavaScript code should not be embedded in HTML information, until the code is restricted to at least one session. HTML code considerably increases the page weight without the potential of discount as a result of caching and compression.

Line length

Avoid strings longer than 80 characters. If the operator does not match on one line, then it have to be moved or cut up. When breaking a line, the subsequent line must be indented eight areas from the start.

In retreat from the settlement, given the fashionable screens and determination, the size of the string might be elevated to 120 characters. Trendy code editors make the highlight of this line, for instance NetBeans, PHPStorm, and its size could be custom-made.


It is essential to attempt to absolutely describe the complicated sections of the code. Developers who will take a look at your code, otherwise you your self after some time need to know what this code does. Comments ought to be nicely written, clearly, appropriately, if the remark isn't full sufficient, and even worse - flawed, which may mislead the developer, on this case it is higher not to write a comment at all.

Equally, feedback shouldn't describe obvious issues, otherwise they'll only waste the reader's time.

i = zero; // Set i to zero.

One other of the helpful properties of feedback is that when writing them in sure guidelines, reminiscent of JSDoc, they can be utilized to generate software code documentation.

Variable declaration

All variables have to be declared before they're used. JavaScript does not require such constructs, however it makes the program a lot easier to read, and this makes it easier to detect non-declared variables, which may be interpreted as international by the interpreter. Assumed, implicit international variables should by no means be used, all variables must be declared solely in an specific method, and using the var operator.

The var construct should go first within the perform body.

Preferably, each variable can be described on a new line and might be added with a remark. Every time attainable, it is higher to maintain the declaration of variables in alphabetical order.

var currentEntry, // presently chosen table entry
      degree, // indentation degree
      measurement; // measurement of desk

In JavaScript, there isn't a variable declaration block, as for example it's current in languages ​​corresponding to pascal, but with a purpose to hold order in the code, it's better to declare variables firstly of a perform.

The use of worldwide variables ought to be stored to a minimum, and implicit declaration of worldwide variables should not be used in any respect.

Perform declaration

All features have to be declared earlier than they're used. Inner features may be declared by way of var. This helps make clear which variables are included within the perform space.

There must be no area between the perform identify and the opening parenthesis of the parameter listing. The area have to be between the closing bracket and the curly bracket of the perform physique. The perform physique itself have to be indented by 4 spaces. The right brace of the perform itself have to be aligned with the road containing the perform declaration.

perform outer (c, d)
    var e = c * d;

    perform inside (a, b)
        return (e * a) + b;

    return inside (0, 1);

If the literal perform is nameless, then there have to be an area between the word perform and the opening bracket of the parameter record. If there isn't any area, there could also be confusion that the identify of the perform is perform, which can appear to be an error when reading the code.

div.onclick = perform (e)
    return false;

that =
    technique: perform ()
        return this.datum;
    datum: 0

The use of worldwide features also needs to be minimized.

When a perform must be referred to as immediately, it is enclosed in parentheses. The results of the work of such a perform shall be the fact that this perform returns, but not a link to the perform itself.

var collection = (perform ()
    var keys = [],
          values ​​= [];

        get: perform (key)
            var at = keys.indexOf (key);
            if (at> = zero)
                return values[at];
        set: perform (key, worth)
            var at = keys.indexOf (key);
            if (at < 0) at = keys.length; keys[at] = key; values[at] = value; , remove: function (key) var at = keys.indexOf(key); if (at >= zero)
                keys.splice (at, 1);
                values.splice (at, 1);


The names of variables or features may be composed of 26 giant and small characters (A .. Z, a ... z), 10 digits of digits (0 .. 9) and the underscore character. It's higher to avoid using worldwide symbols, because reading and understanding them can introduce sure difficulties. Do not use the $ (dollar sign) or (backslash) check in variable and performance names.

Don't use the underscore _ as the first character of the identify. This technique is usually used to discuss with native (personal) variables or features, however doesn't truly provide privacy to those variables. In case your code requires using personal members, then it is best to keep away from the potential for opening this knowledge.

Most variables and features must start with a small letter.

Features constructors that use the brand new operator must begin with a capital letter. When compiling a JavaScript script, or checking code with third-party tools, warnings can be displayed if features or variable names can be used without the brand new construct. The work of a constructor perform that doesn't use the new operator will behave utterly in another way, so the agreement to write down such features with a capital letter is to some extent protection towards error.

International variables that carry the which means of constants, namespaces must be in capital letters, since JavaScript doesn't include such constructs.


Simple operators

Every line must include no multiple operator. Every simple statement should end with a semicolon (;). Observe that the task statement to which the perform is assigned, the literal, should end with a semicolon.

In JavaScript, any expression shall be an operator. This will disguise some errors if these operators use a semicolon on the finish. For instance, this is usually a regular line with a comma at the end, which won't trigger any error and won't break the script.

Compound Operators

Compound statements are statements that include lists of different statements enclosed in (curly braces).

  • Operators inside compound statements have to be indented by four spaces.
  • (Left brace) have to be at the finish of the line by which the compound assertion begins.
  • (Right brace) must be positioned on a brand new line and indented, to align with the start of the line containing the corresponding (left curly bracket).
  • Braces ought to be present all over the place where their presence is possible, it is necessary to keep away from random errors, and for readability of the code.


The presence of break and proceed labels in the code can only be used within the while, for, do, and change constructs.

Operator return

The value of the operator return should by no means be enclosed in () (parentheses). The worth of this assertion should begin on the same line because the return assertion itself, to avoid by chance inserting a semicolon when deciphering or compressing the code.

If statement

The if construct ought to have the following type:

if (situation)

if (situation)

if (condition)
else if (situation)

For operator

The for assertion should have the following development:

for (initialization; condition; update)

for (variable in object)
    if (filter)

The first form of the document serves to work with arrays and cycles with a given variety of iterations.

The second type is used when working with objects. It ought to be borne in thoughts that the members which are added to the prototype of the item can be included in the switch. To do that, use validation utilizing the hasOwnProperty technique to differentiate the true properties of an object:

for (variable in object)
    if (object.hasOwnProperty (variable))

While assertion

The whereas construct should appear to be this:

while (situation)

Do operator

The do statement ought to seem like this:

while (situation);

In contrast to other declared compound operators, this could all the time end; (semicolon).

Change statement

The change statement ought to seem like this:

change (expression)
case expression:

Every case department have to be according to the change assertion. This avoids extreme padding.

Every group of case statements, except default, must finish with a break, return, or throw.

Attempt operator

The attempt statement ought to appear to be this:

catch (variable)

catch (variable)

Operator proceed

Keep away from using the proceed assertion. This operator tends to hide the movement of the perform.

Operator with

With the operator should not be used.


Clean strains improve readability by dividing code into sections which might be logically related.

Areas must be used in the following instances:

  • The key phrase followed by ((left bracket) have to be separated by an area
    whereas (true)
  • An area shouldn't be placed between the perform identify and ((left bracket), in the perform f () construct. This helps to differentiate between key phrases and performance calls.
  • All binary operators except. (factors), ((left bracket) and[(leftsquarebrackets)mustbeseparatedbyaspace[(левойквадратнойскобки)должныбытьразделеныпробелом[(leftsquarebrackets)mustbeseparatedbyaspace[(левойквадратнойскобки)должныбытьразделеныпробелом
  • Every; (semicolon) within the management part of the for construction have to be separated by an area.
  • Spaces must comply with every comma.

In giant tasks it turns into very troublesome to bear in mind all these agreements without using auxiliary instruments and code editors. In line with this, on your own management, there is a want to accumulate these instruments.

Jslint JavaScript code validation software

JavaScript is an interpreted language that doesn't have its own compiler, compared to languages ​​comparable to Java, C ++, which, when constructing a venture or operating, verify the standard of written code, making an allowance for numerous nuances, reminiscent of declared but unused variables, not optimized sections. code, missing semicolons, and so forth. Subsequently, it might be helpful to have a software that might perform the verify and level the developer to varied errors.

One such software is JSLint. JSLint is a program written in JavaScript, the purpose of which is to seek out problems in JavaScript packages.

When C was nonetheless a younger language, there have been a number of widespread programming errors that weren't caught by primitive compilers, so a program referred to as lint was developed to scan the supply file for errors.

When the language reached a certain degree of perfection, compilers began to verify it better and concern the appropriate messages, after which the lint program was not wanted.

JavaScript is a young language. It was originally used to perform small tasks in net pages, duties for which Java was too heavy and clumsy. Presently, JavaScript performs a big position within the net, and is used in giant and sophisticated tasks. Most of the features that have been carried out within the language have been aimed toward making it simple, but when tasks turn into bigger and extra complicated, there's cause for concern due to this performance. Because of this, JavaScript packages need a software like lint.

JSLint takes the javascript supply code and scans it. When a problem is discovered, a message is returned with its description, and its approximate location within the source file. The drawback might not essentially be a syntax error, type checks are additionally carried out, and the code construction is adhered to.

International variables

The largest drawback with javascript is the dependency on international variables that have been implicitly declared. If a variable shouldn't be declared utilizing the var development, then in JavaScript this variable becomes international, as a property of the window object. Due to this, numerous sorts of errors can occur.

JSLint requires that each one variables and features be declared earlier than they are used or referred to as. This lets you easily detect international variables, in addition to a superb tone, and makes it easier to learn the supply code of this system.

Typically the file will depend on international variables and features which are outlined elsewhere. To do that, that you must describe such variables in a particular directive / * international * /, which point out to JSLint that they're used in different information and will not be misguided. Variables in a directive are a comma-separated record of names. Each identify might embrace a colon, after which the flag is about to true or false, which indicates whether the variable was meant for this file or not.

Some international variables might already be outlined initially. Suppose a browser when predetermined are commonplace international properties which might be offered by the browser, reminiscent of document and addEventListener.

/ * international clearInterval: false, clearTimeout: false, document: false, event: false, frames: false, history: false, Image: false, location: false, identify: false, navigator: false, Choice: mum or dad, father or mother: false , display: false, setInterval: false, setTimeout: false, window: false, XMLHttpRequest: false * /

Together with console, alert, features that may be redefined globally, or which may be expanded, or which it's desirable to keep away from within the remaining product.

/ * international alert: false, affirm: false, console: false, Debug: false, opera: false, prompt: false, WSH: false * /


JavaScript makes use of C - an analogous syntax that requires using a semicolon to delimit operators. In JavaScript, setting a semicolon on the end of each assertion is elective, you'll be able to carry out a line feed as an alternative, and such code might be thought-about working for the online browser, however this strategy might entail errors.

JSLint expects each assertion to finish; (semicolon), exceptions in some conditions can solely be for for, perform, if, change, attempt to while statements.


The comma operator can result in overly complicated expressions and can also mask some programming errors.

JSLint expects to see using a comma as a separator, however not as an operator (except initialization and increment of operator elements).

Space of ​​visibility

In lots of languages, a block defines its scope. Variables declared in this block will not be visible outdoors.

In JavaScript, blocks don't define scope. The scope is decided only contained in the perform. The variable defined in the perform might be seen throughout this perform. Blocks in JavaScript on this regard can confuse skilled programmers of different languages, as a consequence of an identical syntax, which, accordingly, can result in errors.

In languages ​​with scopes in blocks, it is usually advisable to declare variables in the place where they are immediately used. However since JavaScript doesn't have a block scope, it's right to declare all variables at the prime of the perform. It is strongly recommended to make use of one var operator in perform. This suggestion might be disabled utilizing the vars choice.

Required Blocks

JSLint assumes that there are operator brackets in if, while, do, and for constructions, regardless of how many operators are present within these constructs.

JavaScript allows the next write technique:

if (condition) statement;

This type of recording is understood to contribute to the looks of errors in tasks. Subsequently, JSLint assumes using the following entry:

if (situation)

Developers expertise exhibits that this type of recording is more strong from errors.

for in

The for in loop is used to enumerate all the properties of an object. But in addition with the assistance of this cycle, completely all properties are seen, together with people who have been inherited by means of the prototype. It seems a nasty aspect effect once we get a way as a property. If such a cycle is written with out consciousness of this example, then this piece of code might trigger an error.

Тело цикла должна быть обернуто в оператор if, который выполняет проверку свойства объекта, для исключения свойств прототипа, например:

for (identify in object)
    if (object.hasOwnProperty(identify))

В большинстве случаев, этого оператора стоит избегать полностью. Лучше всего полагаться на методы, такие как Object.keys и Array.prototype.forEach.


Распространенной ошибкой в операторе change, является то что забывается размещение break после кострукции case. JSLint ожидает, что каждая конструкция case будет заканчиваться break, return или throw. Каждая конструкция case будет выстраивается на одной линии с оператором change.


JavaScript позволяет определять var в любом месте внутри функции. JSLint в этом случае более строго относится к таким определениям.

JSLint ожидает, что конструкция var будет объявлена только один раз, и до того как будет использована.

JSLint отрицательно смотрит на использование конструкции var внутри операторных скобок, так как они не имеют своей области видимости.


Эта конструкция изначально была предназначена для обеспечения сокращенного доступа к свойствам глубоко вложенных объектов. Использование этот конструкции может привести к путанице между использованием переменных и свойств, что может дать непредсказуемое поведение программы. По этому, лучше никогда не использовать этот оператор.

== и !=

== и != операторы выполняют приведение типов перед сравнением. Это плохо, потому что различные конструкции, к примеру такая " trn" == 0 будет true. Это может маскироваться ошибки. JSLint не может достоверно определить, если использование == в настоящее время оправдано, по этому лучше всегда использовать сравнение без неявного приведения типов, а именно === и !==.

С помощью опции eqeq, можно отключить проверку этого оператора.

++ и --

JSLint против использования этих операторов. Включить их спользование можно с помощью опции plusplus.

Битовые операции

В JavaScript нет типа Integer, но есть битовые операторы. Битовые операторы преобразуют операнды с плавающей точкою в целые и обратно, поэтому они не так эффективны как в C или других языках. Они редко бывают полезными в браузерных приложениях. Сходство с логическими операторами может маскировать некоторые ошибки программирования. Опция bitwise разрешает использовать эти операторы.

Eval это зло

Функция eval (и его родственники - setTimeout и setInterval) обеспечивают доступ к компилятору JavaScript. Это иногда необходимо, но в большинстве случаев это указывает на наличие очень плохого стиля программирования. Функция eval является наиболее неправильной особенностью JavaScript.

Конструкторы и new

Конструкторы - это функции, которые предназначены для использования с оператором new. Эта приставка создает новый объект на основе прототипа функции, и связывает этот объект функции с присваиваемой переменной. Если принебречь использованием оператора new для функции конструктора, то возвращаемый результат будет не совсем таким, который ожидался.

JSLint обеспечивает соглашение, что функции конструкторы должны иметь названия первая буква которого будет в верхнем регистре, иначе это будет считаться ошибкой при проверке, если эта функция будет вызываться с оператором new.

Использование оператора new с такими объектами как Number, String, Boolean - будет считаться ошибкой при проверке.

При проверке такой конструкции new Object, JSLint будет подразумевать ее ошибочной, вместо который лучше использовать краткую запись - .


JSLint предлагает несколько опций, которые контролируют его работу. В веб-приложении JSLint, варианты выбираются с использованием флажков и двух полей.

Когда JSLint вызывается как функция, он принимает параметр - объект опций, который позволяет определить приемлемое подмножество JavaScript. На веб-странице версия JSLint http://www.JSLint.com делает это автоматически.

Опции можно также задать в сценарии с помощью / * JSLint * / директивы:

/*jslint nomen: true, debug: true, evil: false, vars: true */

Tolerate task expressionsasstrue if task must be allowed outdoors of assertion place.
Игнорирование битовых операторовbitwisetrue, если битовые операторы не должны проходить проверку
Разрешить функции браузераbrowsertrue, учитываются стандартные глобальные переменные браузера
Разрешить Google Closure идиомыclosuretrue, если Google Closure аннотации должны быть разрешены
Разрешать proceedproceedtrue, для того что бы использование countinue игнорировалось
Предложение CouchDBcouchtrue, если нужо что бы функции CouchDB считались глобальными
Разрешать debggerdebugtrue, если оператор debug должен быть разрешен
Разрешать console, alertdeveltrue, если не установлена опция browser, и нужно что бы эти операторы были разрешены
Разрешить == и !=eqeqtrue, если == и != операторы должны быть разрешены
Разрешить evaleviltrue, если eval должен быть разрешен
Пробелы и отступыindentКоличество пробелов которые используются для отступов (по умолчанию 4)
Максимальное количество ошибокmaxerrМаксимальное количество предупреждений для отчета проверки (по умолчанию 50)
Максимальная длинна строкиmaxlenМаксимальное количество символов в строке
Использование прописных букв в начале слова в названии конструктораnewcaptrue, если первые буквы в именах функций конструктора являются обязательными
Учитывать Node.jsnodetrue, если Node.js должна учитываться в глобальных переменных
Разрешать прочерк _ в индентификаторахnomentrue, если не нужно разрешить использование таких переменных
Остановка на первой ошибкеpassfailtrue, если сканирование должно останавливаться на первой ошибке
Разрешить ++ и --plusplustrue, если использование ++ или -- должно быть разрешено
Разрешить отсутствие "use strict" в начале функцииsloppytrue, для того что бы вставка строки "use strict" была не обязательной
Разрешить TODO комментарииtodotrue, для того что бы не реагировать на TODO комментарии
Разрешить неиспользуемые параметрыunparamtrue, не показывать предупреждений о неиспользуемых параметрах
Разрешить использование множества var в функцииvarstrue, для множественного использования var в функции
Разрешать грязные пробелыwhitetrue, для игнорирования грязных пробелов

Описание работы JSLint, можно посмотреть на официальном сайте