GitHub Copilot Writing Comments
Comments are your most powerful tool for directing GitHub Copilot. A well-written comment is an instruction that Copilot converts into working code. This topic shows you how to write comments that produce accurate, useful suggestions every time.
Why Comments Work as Instructions
Copilot was trained on billions of code files where developers wrote comments above their functions. Over and over, the training data showed the pattern: comment describes intent, code below implements it. Copilot learned this relationship so well that when you write a comment, it confidently predicts the matching code.
TRAINING DATA PATTERN (seen millions of times):
──────────────────────────────────────────────────
// Remove duplicate values from an array
function removeDuplicates(arr) {
return [...new Set(arr)];
}
──────────────────────────────────────────────────
YOUR COMMENT → Copilot matches the pattern → CODE
Comment Placement: Where You Put It Matters
Put the comment on the line immediately before what you want Copilot to generate. Comments that are three or more lines away from the cursor are less likely to influence the suggestion.
EFFECTIVE PLACEMENT:
// Convert temperature from Celsius to Fahrenheit
function celsiusToFahrenheit(celsius) {
←── Copilot suggests here, influenced by comment above
INEFFECTIVE PLACEMENT:
// Convert temperature from Celsius to Fahrenheit
// Other notes here
// More notes
function celsiusToFahrenheit(celsius) {
←── Comment is too far away, suggestion may be generic
Single-Line Comments for Small Tasks
For a single function or expression, one focused comment is enough. Write it as a plain English sentence that says exactly what the code should do.
ONE-LINE COMMENT EXAMPLES:
// Check if a string contains only numbers
const isNumeric = (str) =>
→ Copilot: /^\d+$/.test(str);
// Return the largest number in an array
function findMax(numbers) {
→ Copilot: return Math.max(...numbers);
// Get the first and last elements of an array
const firstAndLast = (arr) =>
→ Copilot: [arr[0], arr[arr.length - 1]];
Multi-Line Comments for Complex Tasks
When a function does several things, use a multi-line comment block. Each line of the comment adds more detail that Copilot can use to produce a complete implementation.
// Register a new user
// 1. Validate that email is not already in use
// 2. Hash the password with bcrypt
// 3. Save user to the database
// 4. Return a JWT token
async function registerUser(email, password) {
→ Copilot generates all four steps as working code
This numbered comment style works especially well. It tells Copilot the exact order of operations and what each step must do. The suggestion becomes a structured implementation of those steps.
JSDoc and Docstring Comments
In JavaScript, JSDoc comments describe parameters and return values. Copilot reads these and generates more precise code because it knows the data types and expected behavior.
JAVASCRIPT JSDoc:
/**
* Calculates the monthly payment for a loan
* @param {number} principal - The loan amount in dollars
* @param {number} annualRate - Annual interest rate as a decimal (e.g., 0.05)
* @param {number} months - Number of monthly payments
* @returns {number} The monthly payment amount
*/
function calculateMonthlyPayment(principal, annualRate, months) {
→ Copilot generates the correct compound interest formula
PYTHON DOCSTRING:
def send_email(to: str, subject: str, body: str) -> bool:
"""
Send an email using the SMTP server.
Returns True on success, False on failure.
Raises ValueError if the email address is invalid.
"""
→ Copilot generates try/except, SMTP setup, and return values
Inline Comments to Guide Copilot Mid-Function
You can place comments inside a function to guide Copilot line by line. After Copilot writes one section of code, add another comment below it to guide the next section.
function processOrder(order) {
// Validate required fields
← Copilot writes validation code here
// Calculate the total with discounts applied
← Copilot writes calculation code here
// Save order to database
← Copilot writes database insert here
// Send confirmation email
← Copilot writes email sending code here
}
This approach gives you fine-grained control. You direct each section while Copilot handles the implementation.
Language-Specific Comment Examples
PYTHON:
# Read a CSV file and return a list of dictionaries
def read_csv(filepath):
→ Copilot: uses csv.DictReader to parse the file
JAVA:
// Create a thread-safe singleton instance
public static synchronized getInstance() {
→ Copilot: implements double-checked locking pattern
SQL:
-- Find all orders placed in the last 30 days
-- Group by customer and show total spend
SELECT
→ Copilot: writes the GROUP BY query with date filter
BASH:
# Delete all log files older than 7 days in /var/log
→ Copilot: find /var/log -name "*.log" -mtime +7 -delete
Comments That Describe Constraints
Copilot responds well to comments that include constraints and edge cases. Adding "without using X" or "handle the case where Y" makes suggestions more precise.
BASIC COMMENT:
// Sort users by last name
CONSTRAINT-RICH COMMENT:
// Sort users by last name alphabetically
// If two users have the same last name, sort by first name
// Handle the case where last name could be null or empty
function sortUsers(users) {
→ Copilot handles all three cases in the suggestion
Avoid Vague Comments
Vague comments produce vague suggestions. The more specific you are, the more accurate Copilot becomes.
VAGUE → POOR SUGGESTION:
// do the thing
function handle(x) {
→ Copilot: console.log(x); ← completely useless
SPECIFIC → GOOD SUGGESTION:
// Convert a Unix timestamp to a human-readable date string
// Format: "Monday, January 15, 2024 at 3:45 PM"
function formatTimestamp(unixTimestamp) {
→ Copilot: uses Date and Intl.DateTimeFormat correctly
Comment as a Specification Document
For larger features, treat comments as a miniature specification. Write out the complete expected behavior before any code. Copilot reads the full comment block and generates an implementation that matches all requirements.
/*
* Shopping Cart Module
* ---
* addItem(productId, quantity): adds or increases quantity
* removeItem(productId): removes item completely
* updateQuantity(productId, qty): updates to new quantity
* getTotal(): returns sum of (price × quantity) for all items
* clear(): empties the cart
*/
class ShoppingCart {
→ Copilot generates all five methods with correct logic
Writing good comments is a skill that pays off beyond Copilot. Clear comments make your code easier for teammates to read, easier to debug six months later, and easier for Copilot to assist with. The habit of writing before coding — thinking through what you need in plain language — improves your code regardless of whether Copilot generates it or you do.
