Комментарий в javascript - ПК журнал
Polytech-soft.com

ПК журнал
15 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Комментарий в javascript

Comments

As we know from the chapter Code structure, comments can be single-line: starting with // and multiline: /* . */ .

We normally use them to describe how and why the code works.

At first sight, commenting might be obvious, but novices in programming often use them wrongly.

Bad comments

Novices tend to use comments to explain “what is going on in the code”. Like this:

But in good code, the amount of such “explanatory” comments should be minimal. Seriously, the code should be easy to understand without them.

There’s a great rule about that: “if the code is so unclear that it requires a comment, then maybe it should be rewritten instead”.

Recipe: factor out functions

Sometimes it’s beneficial to replace a code piece with a function, like here:

The better variant, with a factored out function isPrime :

Now we can understand the code easily. The function itself becomes the comment. Such code is called self-descriptive.

Recipe: create functions

And if we have a long “code sheet” like this:

Then it might be a better variant to refactor it into functions like:

Once again, functions themselves tell what’s going on. There’s nothing to comment. And also the code structure is better when split. It’s clear what every function does, what it takes and what it returns.

In reality, we can’t totally avoid “explanatory” comments. There are complex algorithms. And there are smart “tweaks” for purposes of optimization. But generally we should try to keep the code simple and self-descriptive.

Good comments

So, explanatory comments are usually bad. Which comments are good?

Describe the architecture Provide a high-level overview of components, how they interact, what’s the control flow in various situations… In short – the bird’s eye view of the code. There’s a special language UML to build high-level architecture diagrams explaining the code. Definitely worth studying. Document function parameters and usage There’s a special syntax JSDoc to document a function: usage, parameters, returned value.

Such comments allow us to understand the purpose of the function and use it the right way without looking in its code.

By the way, many editors like WebStorm can understand them as well and use them to provide autocomplete and some automatic code-checking.

Читать еще:  Как восстановить свою почту на майл ру

Also, there are tools like JSDoc 3 that can generate HTML-documentation from the comments. You can read more information about JSDoc at http://usejsdoc.org/.

Why is the task solved this way?

What’s written is important. But what’s not written may be even more important to understand what’s going on. Why is the task solved exactly this way? The code gives no answer.

If there are many ways to solve the task, why this one? Especially when it’s not the most obvious one.

Without such comments the following situation is possible:

  1. You (or your colleague) open the code written some time ago, and see that it’s “suboptimal”.
  2. You think: “How stupid I was then, and how much smarter I’m now”, and rewrite using the “more obvious and correct” variant.
  3. …The urge to rewrite was good. But in the process you see that the “more obvious” solution is actually lacking. You even dimly remember why, because you already tried it long ago. You revert to the correct variant, but the time was wasted.

Comments that explain the solution are very important. They help to continue development the right way.

Any subtle features of the code? Where they are used?

If the code has anything subtle and counter-intuitive, it’s definitely worth commenting.

Summary

An important sign of a good developer is comments: their presence and even their absence.

Good comments allow us to maintain the code well, come back to it after a delay and use it more effectively.

Comment this:

  • Overall architecture, high-level view.
  • Function usage.
  • Important solutions, especially when not immediately obvious.

Avoid comments:

  • That tell “how code works” and “what it does”.
  • Put them in only if it’s impossible to make the code so simple and self-descriptive that it doesn’t require them.

Comments are also used for auto-documenting tools like JSDoc3: they read them and generate HTML-docs (or docs in another format).

Предложение от 8host.com

Написание комментариев в JavaScript

В программировании обычно в первую очередь учитывается то, как компьютер читает и интерпретирует написанный код. Но так же важно учитывать интересы людей, которые будут читать и работать с этим кодом дальше. Нужно уметь правильно комментировать и структурировать свой код, чтобы обеспечить простоту чтения.

Читать еще:  Как восстановить папку которую удалил из корзины

Комментарии – это пометки в исходном коде программы, которые не читаются интерпретатором и поэтому не влияют на фактический вывод кода. Комментарии могут быть чрезвычайно полезны для объяснения целей и действий того или иного блока кода.

Без комментариев разработчикам бывает сложно понять код, написанный другими людьми. Да и вы сами можете просто забыть, для чего добавили в программу тот или иной блок кода. Правильно прокомментированный код поможет вам избежать проблем с поддержкой программы в будущем.

Синтаксис комментариев

В JavaScript есть два типа комментариев.

Однострочные комментарии в JavaScript записываются с помощью двух слешей //.

// This is a comment

Интерпретатор будет игнорировать все символы после // до конца строки.

Многострочные комментарии заключаются в теги /* и */. Если вы знакомы с CSS, вы уже знаете, как работают такие комментарии.

/* This is
a comment */

Интерпретатор будет игнорировать все, что находится между этими тегами.

Все комментарии вне зависимости от их типа пишутся над блоком кода, который они объясняют.

// Print «Hello, World!» to the console
console.log(«Hello, World!»);

Кроме того, комментарии должны находиться на одном уровне с объясняемым кодом.

// Initialize a function
function alphabetizeOceans() <

// Define oceans variable as a list of strings
const oceans = [«Pacific», «Atlantic», «Indian», «Antarctic», «Arctic»];

// Print alphabetized array to the console
console.log(oceans.sort());

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

Встроенные комментарии

Если однострочный комментарий находится в конце строки кода, такой комментарий называется встроенным.

let x = 99; // assign numerical value to x
let y = x + 2; // assign the sum of x + 2 to y

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

Помните, что однострочные комментарии нельзя закрыть тегом. Если в эту строку случайно попадет код программы, интерпретатор пропустит его. Поэтому будьте внимательны, следите, чтобы комментарий не сливался со следующей строкой кода в одну строку.

for (let i = 0; i === 10; i++) // for loop that runs ten times <
// Running this code results in a syntax error
>

Читать еще:  Можно ли восстановить папку удаленную из корзины

Встроенные комментарии бывают очень полезны, но их следует использовать экономно – код с большим количеством встроенных комментариев выглядит грязно и, следовательно, его трудно читать.

Многострочные комментарии

Многострочные комментарии пишутся на уровне блока и представляют собой длинные примечания или описание последующего блока кода. Часто этот тип комментариев размещается в верхней части файла или перед особенно сложным блоком кода.

/* Initialize and invoke a the greetUser function
to assign user’s name to a constant and print out
a greeting. */
function greetUser() <
const name = prompt(«What is your name?»);
console.log(«Hello ,» + name + «! How are you?»);
>
greetUser();

Иногда встречается немного видоизмененный синтаксис: комментарий открывается тегом /**, и каждая строка начинается с символа звездочки.

/**
* Initialize constant with an array of strings.
* Loop through each item in the array and print
* it to the console.
*/
const seaCreatures = [«Shark», «Fish», «Octopus»];
for (const seaCreature of seaCreatures) <
console.log(seaCreature);
>

Иногда эти комментарии также содержат сведения о файле программирования, включая имя, версию и автора сценария.

Комментирование кода для тестирования

Комментарии позволяют игнорировать те или иные блоки кода для тестирования работы программы. Это называется «закомментировать код».

Если в каком-то блоке кода есть ошибка, вы можете попробовать закомментировать отдельные блоки для определения источника проблемы. Вы также можете использовать этот механизм для переключения между блоками кода, которые выдают разные результаты.

// Function to add two numbers
function addTwoNumbers(x, y) <
let sum = x + y;
return sum;
>
// Function to multiply two numbers
function multiplyTwoNumbers(x, y) <
let product = x * y;
return product;
>
/* In this example, we’re commenting out the addTwoNumbers
function, therefore preventing it from executing. Only the
multiplyTwoNumbers function will run */
// addTwoNumbers(3, 5);
multiplyTwoNumbers(5, 9);

Закомментировать код можно с помощью как однострочных, так и многострочных комментариев. Выбор зависит от объема блока, который нужно закомментировать.

Примечание: Комментировать код нужно только на время тестирования. Не оставляйте закомментированные блоки в конечном сценарии.

Комментирование кода может оказаться полезным при разработке логики программы, поскольку так вы можете определить источник ошибок или оценить производительность того или иного блока.

Заключение

Код программы JavaScript читает не только машина, но и другие разработчики и пользователи. Комментарии позволяют сделать код удобочитаемым и более понятным.

0 0 голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты 220 Вольт
Adblock
detector