PROGRAMMING-CONCEPTS

Comment: Definition, Purpose, and Examples

A comment is a piece of text inside your code that the computer completely ignores. It exists only for humans — to clarify intent, explain tricky logic, outline future work, or make the structure of the code easier to follow. Comments are essential for readable, maintainable software, especially when working in teams or returning to old code after weeks or months.

Every major programming language supports comments, but the symbols differ. Regardless of syntax, the purpose is the same: communicate clearly with whoever reads the code next.


Why Comments Matter

Comments turn code from something that merely works into something that can be understood, reused, and extended. They offer value in several situations:

  • You write complex logic that needs a brief explanation
  • You want to document why something is done, not just what it does
  • A workaround or temporary solution exists, and future readers should know
  • You’re planning next steps and want to leave reminders
  • You’re collaborating with others and need predictable, shared context

Good comments reduce cognitive load. They act as signposts in otherwise dense technical terrain.


Comment Syntax Across Popular Languages

Each language uses its own symbols for comments, but the pattern is consistent:

single-line comments for short notes and multi-line comments for longer explanations.

Python

# This function calculates the discounted price

Python also uses multi-line strings (""" ... """) in specific contexts, but the # symbol defines true comments.

JavaScript / TypeScript

// Fetch tasks from API

Multi-line format:

/*
  Load tasks from server
  and update state
*/

This style is widely used across browser code, Node.js, and TypeScript applications.

Swift

// Format a date for display

Multi-line:

/*
  Parse input safely
  before converting to a number
*/

Swift’s comments are nearly identical to JavaScript’s.

HTML and CSS

HTML:

<!-- Navigation section -->

CSS:

/* Highlight active elements */

These help organize markup and styling when working on multi-file web projects.


When to Use Comments

Comments are most useful when they add clarity. The following situations benefit from them.

1. Explaining why something is done a certain way

Not every decision is obvious from code alone.

// The API returns null here if the user has no posts
const posts = data.posts ?? [];

The note gives context that would otherwise be invisible.

2. Describing complex logic

If a section of code performs several operations, a short comment helps future readers approach it confidently.

# Use a sliding window to compute the rolling average

3. Highlighting temporary solutions

Sometimes code uses a workaround until a future refactor.

// TODO: Replace with async API once backend is updated

This prevents confusion later.

4. Documenting functions or components

Brief documentation above functions is a long-standing best practice.

// Converts temperature from Celsius to Fahrenheit
function toF(celsius: number) { … }

Real-World Example: React Component with Comments

Comments often appear inside React components to clarify state changes or rendering conditions.

function Profile({ user }) {
  // If profile is loading, show a placeholder
  if (!user) return <p>Loading...</p>;

  return (
    <section>
      {/* Display basic user information */}
      <h2>{user.name}</h2>
      <p>{user.email}</p>
    </section>
  );
}

JSX comments ({/* ... */}) help document UI sections cleanly.


Real-World Example: Documenting a Function’s Intention

Short comments help communicate the reasoning behind a calculation.

# Normalize scores to a 0–1 range for comparison
def normalize(value, max_value):
    return value / max_value

The logic is simple, but the motivation is valuable.


Real-World Example: Guard Clauses

Developers often add comments before guard clauses to explain why early exits exist.

// No need to continue if query is empty
if (!query) return [];

Even simple expressions can benefit from context.


Commenting in TypeScript for Complex Types

When working with interfaces or generics, comments clarify structure.

// Represents a user returned by /api/user
interface User {
  id: number;
  name: string;
  active: boolean;
}

This avoids confusion when API shapes evolve.


Multi-Line Explanations for Algorithms

Sometimes you need a longer explanation before algorithmic code.

"""
Use binary search because the list is sorted.
This reduces lookup time from O(n) to O(log n).
"""
def binary_search(items, target): …

This moves important reasoning above the implementation.


When Not to Use Comments

Comments should be helpful, not a substitute for clean code. Avoid commenting in these situations:

1. When the code already explains itself

// Increase count by 1
count = count + 1;

This adds no value.

2. When the comment repeats variable names

# Set the username to the username variable
username = name

No meaningful insight appears here.

3. When the code is overly complex

Comments shouldn’t justify messy code. If logic needs multiple paragraphs of explanation, consider refactoring it.

4. When the comment becomes outdated

Stale comments cause confusion and are worse than no comments at all.


Best Practices

The most effective comments follow simple principles:

  • Explain “why,” not “what”
  • Keep comments close to the code they refer to
  • Update or remove comments after refactors
  • Use comments for decisions, assumptions, constraints, or warnings
  • Reserve multi-line comments for meaningful context
  • Use TODO, FIXME, and NOTE sparingly and intentionally

Good comments make code easier to understand without overshadowing it.


Comments vs Documentation

Comments live inside the code. Documentation lives outside it.

  • Comments clarify specific decisions or logic
  • Documentation describes overall behavior, architecture, or APIs

Many teams use both together. Comments help during development; documentation helps at scale.


Summary

A comment is a piece of text that explains code without affecting how it runs. Every major language supports comments, and developers rely on them to add clarity, describe intent, document complex logic, and guide future maintainers. From Python’s # to JavaScript’s // and Swift’s //, comments are a universal tool for writing code that humans can understand. Thoughtful comments make software more maintainable, more collaborative, and easier to navigate.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster