Topic 8 of 59 JavaScript Core Fundamentals Interactive Tutorial

Writing Comments in JavaScript: Single-Line and Multi-Line Syntax

23 mins read Last updated: 22 Aug 2026 14453 views
Quick Summary & Key Takeaway Target Skill Level: Beginner to Advanced ES6+

Bottom-Line Answer: JavaScript (JS) is a high-level, single-threaded, just-in-time (JIT) compiled programming language with first-class functions that conforms to the ECMAScript specification. It powers dynamic client-side web interactivity alongside HTML and CSS, and executes backend server runtimes via Node.js, Deno, and Bun.

Target Audience: Frontend developers, full-stack engineers, students & QA testers.
Prerequisites: Basic HTML semantics & fundamental CSS styling rules.
Primary Use Cases: Dynamic web UI, DOM manipulation, asynchronous REST APIs, Node.js backend services.

What is Writing Comments in JavaScript? Core Concept & Direct Summary

Core Objective & Problem Statement

How do you write comments in JavaScript and why are JSDoc comments used?

Direct Answer Summary
Use // for single-line comments and /* ... */ for multi-line comments. JSDoc formatting (/** ... */) documents types and functions for IDE intelligence.

Here's a truth every developer learns the hard way:you will forget your own code.That clever program you wrote today? In three months, it will look like a stranger wrote it — and you'll waste an hour figuring out what you meant.

Comments solve this. They'renotes written directly inside your code— for humans only. JavaScript reads every line of your programexceptcomments, which it skips completely.

You already used comments briefly when we built your first program. Now let's master them properly — the two syntaxes, the keyboard shortcuts that make commenting instant, and the professional habits that separate readable code from a confusing mess.

How Does Writing Comments in JavaScript Work? In-Depth Mechanics & Architecture

Comments explain business logic, complex algorithms, and disable code during debugging. Minification tools strip non-essential comments during production builds.
Tutorial illustration

What Is a Comment?

Acommentis text in your code that JavaScriptcompletely ignoreswhen running your program.

script.js
Run Online
// This entire line is a comment — JavaScript skips it!let price = 500;   // Comments can also sit beside codeconsole.log(price); // Output: 500

When this runs, JavaScript behaves as if the comments don't exist. The output is exactly the same with or without them.

So why bother?Because code has two audiences:

  1. 🖥️The computer— needs perfect syntax, zero explanation
  2. 🧑Humans(teammates, future you) — need to understandwhythe code exists

Comments serve the second audience. And here's the industry secret:code is read 10x more often than it's written.Comments are a love letter to whoever reads your code next — which is usually you.


1️⃣ Single-Line Comments: //

Two forward slashes turneverything after them on that lineinto a comment:

script.js
Run Online
// Ask the user for their namelet userName = "Priya";
// Calculate the total with 18% taxlet total = 500 + (500 * 0.18);
console.log(total);
// 590

Three Ways to Use Single-Line Comments

① Full-line comment— explains the next block of code:

script.js
Run Online
// Convert the temperature from Celsius to Fahrenheitlet fahrenheit = (celsius * 9/5) + 32;

② End-of-line comment— a quick note beside the code:

script.js
Run Online
const MAX_USERS = 100;
// server limit — do not increase!

③ Stacked comments— multiple//lines for longer explanations:

script.js
Run Online
// Free delivery rules:
// - Order must be ₹500 or more
// - User must be logged in
// - Remote areas are excluded
if (cartTotal >= 500 && isLoggedIn && !isRemote) {
  console.log("Free delivery applied! 🚚");
}

2️⃣ Multi-Line Comments: /* */

For longer explanations, wrap text in/*and*/— everything between them becomes a comment, across as many lines as you want:

script.js
Run Online
/*
  Discount Calculator
  -------------------
  Author:  Your Name
  Created: Lesson 8 practice
  Purpose: Applies member discounts to the cart total
           and logs the final price to the console.
*/let cartTotal = 1000;
let memberDiscount = 0.15;
let finalPrice = cartTotal -(cartTotal * memberDiscount);
console.log(finalPrice);
// 850

Multi-line comments can also sit mid-line:

script.js
Run Online
let price = /* after tax */ 590;
let result = calculate( /* quantity */ 5, /* rate */ 120);

This works, but use it sparingly — it can make lines hard to read.

⚠️ The Classic Multi-Line Trap: No Nesting!

Youcannotput a/* */comment inside another/* */comment:

script.js
Run Online
/*
  Outer comment starts here...
  /* inner comment */ ← ❌ The FIRST */ ends everything! This line is now live code → SyntaxError!*/

JavaScript ends the comment at thefirst*/it finds — everything after breaks. This bites every developer at least once.

3️⃣ JSDoc Comments — The Professional Upgrade

There's a third style you'll see in real projects:JSDoc. It uses/** */(note the double star) to document functions in a structured way:

script.js
Run Online
/**
 * Calculates the final price after applying a discount.
 *
 * @param {number} price    - The original price
 * @param {number} discount - Discount as a decimal (e.g. 0.15 = 15%)
 * @returns {number} The discounted final price
 */function applyDiscount(price, discount) {
  return price -(price * discount);
}

Why this is magic:in VS Code, hover your mouse overapplyDiscountanywhere in your project — a tooltip pops up showing this documentation automatically! 🤯 JSDoc turns your comments into a live manual for your code. You'll use it heavily once we reach the functions lesson.


⌨️ Keyboard Shortcuts: Comment Like a Pro

Nobody types//on every line manually. Memorize these two VS Code shortcuts — they're among the most-used keys in all of programming:

ActionWindows / LinuxMac
Toggle line commentCtrl + /Cmd + /
Toggle block commentShift + Alt + AShift + Option + A

The workflow:select 10 lines of code → pressCtrl + /→all 10 lines instantly commented. Press again → uncommented. This takes 0.2 seconds, and you'll do it hundreds of times a day.


🐛 Commenting Out Code — The Debugging Superpower

Comments aren't just for notes. One of the most practical uses istemporarily disabling codewithout deleting it — called"commenting out."

Testing two different approaches? Comment one out instead of deleting:

script.js
Run Online
// let greeting = "Hello, " + userName + "!";   ← old way, saved for reference
let greeting = `Hello, ${userName}!`;
← new way, currently activeconsole.log(greeting);

Hunting a bug? Disable sections to isolate the problem:

script.js
Run Online
let total = 500;
// total = total + tax;      ← temporarily disabled: is THIS line the bug?
// total = total - discount; ← and this one?
console.log(total);
// 500 — so the bug is in one of the disabled lines

This technique pairs perfectly with theconsole.log()debugging you learned inLesson 2: comment out code, log values, narrow down the problem, restore the code.

⚠️ One rule:"commenting out" is atemporarytool. If code stays commented-out for weeks, delete it — old dead code confuses everyone. (Your Git history remembers it forever anyway.)

When to Comment (And When NOT To)

Here's where beginners go wrong inbothdirections — writing zero comments, or writing a comment for every single line. The professional balance:

✅ DO Comment: The "Why"

script.js
Run Online
// We add a 500ms delay because the animation// needs time to finish before the modal appearssetTimeout(openModal, 500);
// Round to 2 decimals — floating point math makes// prices like 19.900000000000002 otherwiseprice = price.toFixed(2);

The code showswhathappens; the comment explainswhy— that's the valuable part.

❌ DON'T Comment: The Obvious

script.js
Run Online
let age = 25;
// ❌ BAD: "set age to 25" — the code already says this!
age = age + 1;
// ❌ BAD: "add 1 to age" — yes, we can see that
console.log(age);
// ❌ BAD: "log the age" — congratulations on the obvious

Comments that repeat the code add noise, not value. Worse, they becomelieswhen someone updates the code but forgets the comment.

🏆 The Golden Rule

Good code explains WHAT it does. Good comments explain WHY it does it.

❌ Useless Comment✅ Useful Comment
// loop through users// only process the first 100 users — API rate limit
// add tax// GST is 18% for digital services as of 2024
// check if true// admin accounts bypass the approval step

Common Beginner Mistakes (And Fixes)

❌ Mistake🔍 What Happens✅ Fix
Using#for comments (Python habit)SyntaxErrorJavaScript uses//—#is Python/shell
Nesting/* */inside/* */Comment ends early, code breaksNever nest block comments
Commenting the obviousNoisy, unmaintainable codeComment thewhy, not thewhat
Leaving commented-out code foreverConfusing graveyard codeDelete it — Git remembers
Updating code but not the commentComment becomes a lie 😱Update comments with the code, always

Quick Self-Check: Lesson 8 Quiz 🧠

  1. What are the two comment syntaxes in JavaScript?
  2. Does JavaScript run commented code?
  3. What's the VS Code shortcut to comment/uncomment a line?
  4. Why can't you nest/* */comments inside each other?
  5. Rewrite this bad comment as a good one:let tax = 0.18; // set tax to 0.18

(Answers: 1.//for single-line and/* */for multi-line · 2. No — comments are completely ignored at runtime · 3. Ctrl + / (Windows) or Cmd + / (Mac) · 4. JavaScript ends the comment at the FIRST*/it finds, leaving the rest as broken live code · 5. Something like:// GST rate for digital services (18% as of 2024)— explains WHY, not WHAT)

JavaScript Decision Matrix & Syntax Comparison

Understanding the mechanical differences between variable declarations and execution environments is critical for writing performant, bug-free modern JavaScript.

Variable Declarations: var vs let vs const
Feature / Propertyvar (Legacy ES5)let (Modern ES6+)const (Modern ES6+)
ScopeFunction ScopeBlock Scope ({})Block Scope ({})
Hoisting BehaviorHoisted (initialized as undefined)Hoisted (Temporal Dead Zone - ReferenceError)Hoisted (Temporal Dead Zone - ReferenceError)
Reassignable✓ Yes✓ Yes✗ No (Immutable binding)
Redeclarable in Same Scope✓ Yes (Error-prone)✗ No (SyntaxError)✗ No (SyntaxError)
Window Object BindingCreates property on windowDoes not attach to windowDoes not attach to window
Environment Decision Matrix: Browser Client-Side vs Node.js Server-Side
DimensionClient-Side (Web Browser)Server-Side (Node.js / Deno)
Global Objectwindow, document, navigatorglobal, process, globalThis
DOM & UI Manipulation✓ Full access (document.querySelector)✗ No DOM (Headless / Non-UI)
File System & OS Access✗ Blocked (Sandboxed security)✓ Full access (fs, os, child_process)
Primary FocusInteractive UI, animations, client stateREST APIs, microservices, databases, I/O streaming

Runnable JavaScript Code Example & Practical Implementation

script.js
Run Online
// Single line comment
/*
   Multi-line block comment
*//**
 * Calculates square of a number
 * @param {number} n
 * @returns {number}
 */function square(n) {
  return n * n;
}

Frequently Asked Questions & Technical Interview Insights

Technical Interview & Viva Questions

Frequently asked questions for frontend & full-stack roles
Q

Q: Do comments affect code execution performance in production?

A: No, production build tools and minifiers remove comments prior to deployment.

Related Tools, Tutorials & Authoritative References

Recommended Interactive Tools

Authoritative Standards & Citations