Comments
Learn how to use comments to explain and document your JavaScript code.
What are Comments?
Comments are notes in your code that the JavaScript engine ignores.
They help you explain what your code does, making it easier to read and maintain.
Why Use Comments?
Comments are crucial for teamwork and for your own future reference.
Single-Line Comments
Use // for short, single-line comments:
// This is a single-line comment
let age = 18;Single-line comments are great for explaining a specific line.
Multi-Line Comments
Use /* */ for longer, multi-line comments:
/*
This is a multi-line comment
describing what happens below
*/
let name = "Shyam";Multi-line comments are helpful for describing a block of code or a function's purpose.
Inline Comments
You can also place comments at the end of a line:
let price = 99; // store product priceThese are good for clarifying small details.
Best Practices
Writing good comments makes your code easier to read and maintain. Keep these tips in mind:
-
Keep comments concise and meaningful - Avoid restating obvious code, for example:
let x = 10; // set x to 10Instead, use comments to explain why something is done or provide important context
-
Clarify complex logic with comments - If the code is not immediately clear, add a comment to help future readers understand:
// Check if the user is over 18 and has a valid ID if (age >= 18 && hasValidID) { // Allow access } -
Use consistent formatting - For example, start all comments with a capital letter.
-
Keep comments up to date - If you change your code, remember to update the comments as well. Comments should describe the reason behind the code, not just what it does.
Example
// Calculate area of a circle
let radius = 5;
let area = Math.PI * radius * radius; // uses formula πr²Comments like these help future you (or other developers) understand your thinking.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on
Statements, Semicolons, and Whitespace
Understand how JavaScript statements, semicolons, and whitespace work together.
Variables
In JavaScript, variables are used to store data. They are an essential part of any programming language, as they allow you to store, retrieve, and manipulate data in your programs.