Course Content
Introduction to TypeScript
Introduction to TypeScript
Comments
Q: What does a programmer do when they need to write documentation for their code?
A: They write it in a Word file.
Q: What does a good programmer do when they need to write documentation for their code?
A: They use comments.
Let's turn you into a good programmer and also teach you how to use comments within your code. But first, let's find out what they are:
In TypeScript, there are two types of commenting:
- We can comment out an entire line using
//
; - We can also comment out a block of code spanning multiple lines or a single-line code fragment using
/* code */
.
Let's take a look at an example where we need to comment out some lines and write comments there. I'll repeat, the compiler won't execute or even look at the commented-out code fragments, so we can write anything there (except for bad words; my mom scolds me if I write those).
console.log("Hello world!") // This code performs output of information to the screen. let word : string = 'c<>definity' console.log(`Hello ${word}!`) /*This code creates a variable of type string and uses it for output to the screen. We use this variable with the required syntax and successfully display text on the screen with the variable. */
As you can see in the code above, we have commented out various text fragments. In comments, we write explanations of what is happening in the code and what certain lines do. Notice that when commenting out multiple lines, we use a different comment syntax. (/* */
)
After //
, everything to the right of the characters is commented out.
We can also comment out code fragments. For example, if we suspect an error in a particular line, we can comment out that line and run the code again to check that line for errors.
//var str = 'Hello World"; var num = 132; console.log(num/* - str*/);
Above, we have commented out code fragments in which we suspect errors using different types of comments. Personally, I often identify error-prone areas in code using this method, and I recommend that you do the same. It's a useful skill for a good programmer.
Also, don't forget to write documentation for your code. It's like placing a bottle of water next to your bed after a night of drinking.
Thanks for your feedback!