JavaScript Comments
- JavaScript comments are used to add notes or explanations inside code
- Comments are ignored by the JavaScript engine during execution
- They help developers understand and maintain code easily
- JavaScript supports two types of comments: single-line and multi-line comments
What are JavaScript Comments?
JavaScript comments are lines of text written inside a program to explain what the code does. Comments are not executed by the browser or JavaScript engine, which means they do not affect the output of the program.
Developers use comments to make code easier to read, understand, and maintain. They are also useful when debugging programs or temporarily disabling a piece of code.
Why Use Comments in JavaScript?
Comments explain the purpose and working of code.
They make programs easier for other developers to understand.
Comments can temporarily disable code while testing.
They help maintain proper documentation inside programs.
Types of JavaScript Comments
JavaScript provides two types of comments:
- Single-line comments
- Multi-line comments
1. JavaScript Single-Line Comments
Single-line comments are used when you want to write a comment on only one line.
They start with two forward slashes //.
// This is a single-line comment
let name = "Shivam";
console.log(name);
Example Explained
//
It tells JavaScript that the following text is a comment.
let
It creates a variable to store a value.
console.log()
It displays output in the browser console.
2. JavaScript Multi-Line Comments
Multi-line comments are used when comments need multiple lines.
They start with /* and end with
*/.
/*
This is a multi-line comment.
It can contain multiple lines of text.
*/
let age = 21;
console.log(age);
Using Comments to Disable Code
Developers can use comments to temporarily stop a line of code from executing. This is helpful while testing and debugging.
// console.log("This will not run");
console.log("Hello JavaScript");