- Clarifying Code with Javascript Comments
- Writing Javascript Comments
- Single Line Comments
- Multiline (Block) Comments
- Using Javascript Comments to Prevent Code Execution
- Commenting Out Function Calls
- Commenting Out Function Bodies — Without Return Values
- Commenting Out Function Bodies — With Return Values
- Writing Effective Javascript Comments
- Conclusion
- Комментирование кода в JavaScript — типы и передовые методы
- Однострочные комментарии
- Многострочные комментарии и строки документации JavaScript
- Использование комментариев для отладки
- Хорошие практики комментирования
- Вывод
Clarifying Code with Javascript Comments
Javascript is built for simplicity and ease of use, but it’s still possible to create complex code that isn’t easy to understand at a glance. For these situations, the Javascript standard provides two ways to create code comments where developers can explain in plain language what is happening.
Although a browser doesn’t execute Javascript comments, including comments is an important best practice in software development. Nearly all Javascript code can benefit from the addition of comments to explain how it works; adding useful comments is a sign of good code quality.
This article covers how to create Javascript comments, how they’re used within a program, and some best practices for creating the most effective comments possible.
Writing Javascript Comments
There are two different ways to write comments in Javascript: on a single line or on multiple lines. The syntax for each comment type is slightly different, but there can be some overlap between them stylistically if a developer prefers.
Single Line Comments
Single line Javascript comments start with two forward slashes (//). All text after the two forward slashes until the end of a line makes up a comment, even when there are forward slashes in the commented text.
// This is a single line comment. x = 5; // This is a single line comment as well! // This is a single line comment containing a URL: http://example.com
A group of single line comments makes more extensive commenting possible, and Javascript also supports multiline (block) comments, as shown in the next section.
// This is an example of single line comments // emulating multiline comments. // After three lines or so, block comments // are usually easier to maintain.
Multiline (Block) Comments
Javascript multiline comments, also known as block comments, start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/). They do not require a comment delimiter character on every line and may contain newlines.
/* This is a multiline comment that can span as many lines as you have the patience to compose for your future self. */
Multiline comments, also known as comment blocks, are helpful when documenting complex logical flows within if else statements, error handling in try catch statements, and complex properties and behaviors in Javascript objects.
/* The following tests whether a variable has a value of 1, 2, or 3, then does something different depending on each value. A useful if statement in production code would have more detailed instructions, and this comment would be more detailed as well. */ if (x == 1) < . instructions . >else if (x == 2) < . instructions . >else if (x == 3)
Using Javascript Comments to Prevent Code Execution
Since Javascript comments are not executed, they’re a good way to prevent code execution while testing new features. This strategy allows you to locate bugs, progressively removing comments until you find the problematic code.
Commenting Out Function Calls
When creating a new function, it’s often helpful to make sure that the function doesn’t impact any other code negatively or unexpectedly. A common testing strategy is to comment out the new function, then make sure the rest of a program still runs as expected without it.
This example comments out a call to a newly implemented method to make sure it hasn’t affected the rest of the program before testing the method itself. Despite the function for changing the value of “X” existing in the code, the commented out method call prevents the function’s execution.
function doSomething(x) < let val = x / 2; return val; >let x = 1; let y = 4; // x = doSomething(y); // call is commented out, "x" doesn't change
Commenting Out Function Bodies — Without Return Values
It isn’t always necessary to comment out an entire function when testing. If a function doesn’t return a value, you can comment out the body of the function using a Javascript multiline comment. In this case, the function itself would be called, but the value of “X” still wouldn’t change because nothing inside the function would execute.
let x = 1; function doSomething(z) < /* let a = z * z; x = a / 2; */>doSomething(12);
Commenting Out Function Bodies — With Return Values
The previous technique won’t work the same way if the function immediately assigns its result to a variable; commenting out the function body makes the function return an undefined value. The undefined value then changes the value of “X”, which could confuse testing.
function doSomething(z) < /* let val = z / 2; return val; */>let x = 1; let y = 4; x = doSomething(y); // "X" would be undefined; may not be desirable
Careful commenting allows developers to pinpoint bugs and track how code works, but it’s easy to introduce unexpected behavior without meaning to while commenting, as the previous example shows. Always make sure you account for any ambiguity your comments may create in testing.
Writing Effective Javascript Comments
Finding the right balance between too many comments and too few, or deciding on which style of comments is best for a certain piece of code, is an ongoing debate among developers, one that is unlikely to be resolved anytime soon. Some codebases follow a formal commenting scheme, while others don’t.
Developers have different preferences for when to use single line or multiline comments, but maintaining a consistent strategy when commenting code ensures that comments are clear regardless of the form they take. Some programmers use single line comments for everything, while others use multiline comments everywhere; some programmers only use block comments for formal documentation, while others use them for any long comment that takes up more than a certain number of lines.
The key to effective Javascript comments, no matter what style you use, is to be consistent. As long as your comments are clear and give developers a walkthrough of how your code works, it doesn’t matter exactly what those comments look like.
Conclusion
Javascript comments explain what code does and clarify the decisions behind code design They also prevent execution of code if necessary.
It’s important to use comments well; too few or too many comments will make code harder to understand than if there were no comments at all. Using the right amount of Javascript comments appropriately can help developers use and maintain code for a long time.
Enroll in our Intro to Programming Nanodegree Program today to learn more about Javascript comments and other programming concepts.
Комментирование кода в JavaScript — типы и передовые методы
Основная цель написания кода — чтобы компьютер мог интерпретировать его как команды. Однако также важно, чтобы код, который мы пишем, также легко интерпретировался другими разработчиками.
Вы когда-нибудь возвращались к проекту и испытывали трудности с пониманием внутренней логики? Вероятно, это потому, что указанный проект не был прокомментирован должным образом.
Комментарии — это заметки, написанные в коде, которые игнорируются движком JavaScript, что означает, что они никоим образом не влияют на вывод. Их единственная цель — описать, как и почему код работает, другим разработчикам и вам самим.
В этой статье мы рассмотрим, как комментировать код JavaScript, какие типы комментариев существуют, а также некоторые передовые практики.
Однострочные комментарии
Однострочные комментарии обычно используются для комментирования части или всей строки кода. Однострочные комментарии в JavaScript начинаются с // . Интерпретатор будет игнорировать все, что находится справа от этой управляющей последовательности, до конца строки.
Давайте посмотрим на пример однострочного комментария в действии:
// Print "Hello World" in the console console.log("Hello World");
Здесь мы используем однострочный комментарий, чтобы описать, что делает следующая строка кода.
Если однострочный комментарий появляется в конце строки кода, он называется встроенным комментарием.
Обычно они используются для добавления быстрых аннотаций:
let c = a + b; // Assign sum of a, b to c
Многострочные комментарии и строки документации JavaScript
Если мы хотим добавить примечание, которое занимает несколько строк, мы можем выбрать многострочные комментарии или комментарии на уровне блока.
Многострочные комментарии начинаются /* и заканчиваются */ :
/* The following program contains source code for a game called Tic-tac-toe. It is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner */
Здесь многострочный комментарий используется для описания крестиков-ноликов. Как правило, многострочные комментарии используются для введения и объяснения раздела кода, где одной строки / предложения недостаточно.
Часто можно увидеть и другой тип многострочного комментария:
/** * The following program contains source code for a game called Tic-tac-toe. * It is a paper-and-pencil game for two players, X and O, who take turns marking the * spaces in a 3×3 grid. * The player who succeeds in placing three of their marks in a horizontal, vertical, or * diagonal row is the winner */
Часто эти комментарии могут включать информацию о выполняемом коде, такую как параметры функции или даже автора кода:
/** * Function that greets a user * @author John * @param name Name of the user * @return Greeting message */ function greetUser(name) < return `Greetings, $!`; >
Эти комментарии называются DocStrings, поскольку они по сути являются строками (комментариями), составляющими документацию вашего кода.
Эти типы комментариев действительно полезны для других разработчиков в вашей команде, так как вы можете уточнить, каковы ожидаемые входные данные, каковы выходные данные, а также к кому обращаться в случае необходимости.
Дополнительным преимуществом является то, что вы можете создавать документацию на основе этих строк документа.
Использование комментариев для отладки
Помимо заметок, комментарии также можно использовать для быстрого предотвращения выполнения кода в целях отладки. Это возможно, потому что движки JavaScript не интерпретируют закомментированный код.
Если есть ошибочная строка, которая вызывает проблемы, мы можем просто «закомментировать ее», чтобы отключить ее, не удаляя строку. Это может быть связано с реальными отладчиками, чтобы помочь вам оценить, что происходит.
console.log("Working code"); console.log("Erroneous code);
Если мы хотим удалить второй оператор, но не хотим удалять его навсегда, мы можем просто закомментировать его:
console.log("Working code"); //console.log("Erroneous code);
Совет: в большинстве редакторов кода мы можем использовать сочетание клавиш Ctrl + / для Windows и Cmd + / для Mac, чтобы закомментировать одну строку кода.
Кроме того, вы также можете закомментировать целые разделы, если не уверены, удалять ли их или нет:
/*console.log("Entering for loop"); for (let i = 0; i < 100; i++) < console.log(i); >*/
Хорошие практики комментирования
Во-первых, комментирование — это не повод для написания нечитаемого кода, а затем просто исправить его пятью абзацами комментариев, объясняющих его. Сначала мы должны сосредоточиться на написании чистого, не требующего пояснений кода, который позже можно улучшить с помощью конструктивных комментариев.
Используйте комментарии, чтобы объяснить, почему вы что-то сделали, а не как вы это сделали. Если вы обнаружите, что объясняете, как вы что-то сделали, то пора сделать шаг назад и реорганизовать ваш код в нечто самоочевидное.
Еще один совет — не писать очевидные и излишние комментарии. Например, совершенно не нужен следующий комментарий:
// Prints out the result console.log(result)
Существуют полезные инструменты, такие как JSDOC 3, которые могут создавать документацию только на основе комментариев в вашем коде, которые отформатированы как DocStrings, описанные выше.
Вывод
В этой статье мы рассмотрели, что такое комментарии и как их создавать в JavaScript. Мы рассмотрели различные типы комментариев — однострочные и многострочные комментарии, а также строки документации JavaScript.
Мы также увидели, как отлаживать наш код, используя технику, называемую «комментирование», и, наконец, подытожили некоторые хорошие практики комментирования.