Comments
- Dart course
- Beginner
- Lesson 4/116
- 3 min
Learn to write // and /* */ comments in Dart.
Comments
A comment is text the compiler ignores. It is used to leave notes explaining the code. Dart has two kinds of comments.
Use // for a single-line comment; it lasts until the end of the line. Use /* ... */ for a block comment spanning multiple lines.
There are also documentation comments starting with ///; external tools collect them. For now we use // and /* */.
When to write comments
Comments are most valuable to explain why the code is written that way. The code already shows what it does; so avoid useless comments like // multiply a by 2.
Temporarily disabling a line (turning it into a comment) is also common. This is called commenting out.
Adding a comment at the top of the file explaining its purpose helps you recall the context quickly when you return.
Practice Comment and output
Write a program that has a // comment line and uses print to output Comment did not run. The comment content does not matter; it just needs to exist.
Starter code
// Add a comment and a printSample solution
void main() {
// This line is ignored
print("Comment did not run");
}Expected output
Comment did not run
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Single-line comment
____ This line is ignored by the compiler
// This line is ignored by the compiler
Explanation: A line starting with // is a comment.
2 Which marks start a multi-line comment?
- # ... #
- -- ... --
- /* ... */ Correct answer
- // ... //
Explanation: The other marks are not comments in Dart.
3 Comment types
| Term | Meaning |
|---|---|
// |
Single-line comment |
/* */ |
Multi-line comment |
/// |
Documentation comment |
print |
Prints output |