JavaScript Comments


Comments are lines in your code that are not executed. They're used to explain what your code does, make it more readable, or temporarily disable code while testing.


Comments are ignored by the browser, but they’re incredibly helpful for both you and other developers who read your code.


Types of Comments in JavaScript

JavaScript supports two types of comments:


1. Single-line Comments

Use // to add a comment on a single line.

// This is a single-line comment
console.log("Hello"); // This is also a commen

  • Best for short notes or explanations.
  • Can also be placed after code on the same line.

2️. Multi-line Comments

Use /* */ for comments that span multiple lines.

/*
This is a multi-line comment.
It can explain things in more detail.
*/
console.log("Hello again!");
  • Great for longer explanations or temporarily disabling blocks of code.

Why Use Comments?

  • To explain why something is done a certain way
  • To label sections of code
  • To debug or disable code temporarily
  • To make your code easier to understand when you come back to it later

Don't Do This

Avoid over-commenting obvious things:

let x = 5; // Set x to 5  (too obvious)

Instead, use comments where they actually add value:

// Get the current time in hours
let hour = new Date().getHours();