JavaScript and TypeScript course ยท Module 1: JavaScript Basics

Comments and Code Formatting

8 min read ยท
In this lesson7

In Jurassic Park, good documentation and careful information management are crucial for safety - both for employees and guests. One imprecise description of dinosaur behavior or unreadable notes regarding a safety procedure can lead to catastrophic consequences.

Similarly, in the world of JavaScript, comments and proper code formatting are fundamental practices that ensure your code will be understandable, easy to maintain, and safe.

Comments in JavaScript

Comments are fragments of text in code that are ignored by the JavaScript interpreter. They serve solely for programmers to document code, explain its behavior, or temporarily disable code fragments during testing.

Single-line Comments

A single-line comment starts with two forward slashes (//). Everything to the right of these characters on a given line is treated as a comment.

// This is a single-line comment
let velociraptorCount = 3; // Number of Velociraptors in paddock B

Multi-line Comments

Multi-line (block) comments start with /* and end with */. Everything between these markers is treated as a comment, even if it spans multiple lines.

/*
   This is a multi-line comment.
   It can span several lines.
   Safety protocol for the T-Rex enclosure:
   1. Check fence power supply
   2. Ensure all gates are closed
   3. Monitor activity every 15 minutes
*/

let safetyChecklist = ["power", "gates", "monitoring"];

Practical Uses of Comments

Comments in JavaScript serve various purposes, similar to different types of documentation in Jurassic Park:

1. Code Documentation

/**
 * Calculates the safe distance from a dinosaur enclosure.
 * @param {string} dinoType - The dinosaur species
 * @param {number} dinoCount - Number of dinosaurs in the enclosure
 * @param {boolean} isElectricFenceActive - Whether the electric fence is active
 * @returns {number} Safe distance in meters
 */
function calculateSafeDistance(dinoType, dinoCount, isElectricFenceActive) {
    // Function implementation...
    return distance;
}

This form of comments (JSDoc) is particularly useful because many code editors (like VS Code) use it to display documentation while writing code.

2. Explaining Complex Logic

// Velociraptor escape pattern prediction algorithm
// Based on analysis of 10 previous escape attempts
// and uses the behavior pattern described by Dr. Grant
if ((attemptTime > sunsetTime && attemptTime < sunriseTime) &&
    (weatherCondition === 'storm' || fencePowerLevel < 80)) {
    // Elevated escape risk - activate additional security measures
    activateSecondaryContainment();
}

3. Temporarily Disabling Code (Commenting Out)

// Old feeding method - currently unused
// function feedDinosaurs(dinoType) {
//     if (dinoType === 'herbivore') {
//         providePlants();
//     } else {
//         provideMeat();
//     }
// }

// New feeding method accounting for special diets
function feedDinosaurs(dinoType, specialDiet) {
    // Implementation accounting for special diets
}

4. TODO/FIXME/NOTE Markers

// TODO: Add support for a new species in the feeding schedule
// FIXME: Fix the bug in counting dinosaurs during rain
// NOTE: The park API may change next month

Such markers are often highlighted by code editors and can be easily found when working on code.

Best Practices for Comments

Just as in Jurassic Park, where outdated or misleading information can be dangerous, in code, poor commenting practices can lead to problems:

What to Do:

  1. Write comments that explain "why," not "what"

    // BAD:
    // Increases the dinosaur count by 1
    dinoCount++;
    
    // GOOD:
    // Account for the newly hatched specimen from the laboratory
    dinoCount++;
  2. Keep comments up to date When you change code, also update the comments. Outdated comments are worse than no comments.

  3. Use clear and precise language Just as in safety protocols, clarity is key.

What to Avoid:

  1. Over-commenting

    // BAD:
    // Declaration of a variable with the number of dinosaurs
    let dinoCount = 15;
    
    // GOOD: (no comment needed, the code is self-documenting)
    let dinoCount = 15;
  2. Comments that obscure the code

    /* Warning! This code is complicated and only a senior can understand it.
       Modify at your own risk! */
  3. Outdated comments

    // BAD:
    // Checks if there are 7 dinosaurs
    if (dinoCount > 10) { // The code changed, but the comment remained outdated

Code Formatting

Just as precise maps and plans of Jurassic Park are essential for effective management, proper JavaScript code formatting is crucial for readability and maintenance.

Indentation and Spacing

Consistent use of indentation (usually 2 or 4 spaces) helps visually distinguish code blocks:

function checkParkSecurity() {
    if (fencesActive) {
        // Level 1 indentation
        for (let sector of parkSectors) {
            // Level 2 indentation
            if (sector.hasCarnivores) {
                // Level 3 indentation
                runExtraChecks(sector);
            }
        }
    } else {
        // Level 1 indentation
        activateEmergencyProtocol();
    }
}

Curly Braces

There are two main styles for placing curly braces:

K&R Style (Kernighan & Ritchie)

function checkFences() {
    if (powerLevel < 50) {
        sendAlert();
        activateBackupGenerator();
    } else {
        logStatus("Fences operating correctly");
    }
}

Allman Style

function checkFences()
{
    if (powerLevel < 50)
    {
        sendAlert();
        activateBackupGenerator();
    }
    else
    {
        logStatus("Fences operating correctly");
    }
}

In JavaScript, the K&R style is more common.

Naming Conventions

Just as with precise dinosaur naming, in JavaScript you should follow clear naming conventions:

// camelCase for variables and functions
let velociraptorCount = 3;
function checkSecuritySystems() { }

// PascalCase for classes and constructors
class DinosaurPaddock { }

// UPPER_CASE for constants
const MAX_VISITORS_PER_TOUR = 8;
const PARK_OPENING_HOURS = {
    start: 8,
    end: 20
};

Spaces Around Operators

For improved readability, it's worth using spaces around operators:

// Hard to read
let safetyRating=parkSectors.length>0?parkSectors.filter(s=>s.securityLevel<3).length/parkSectors.length*100:0;

// Easier to read
let safetyRating = parkSectors.length > 0
    ? parkSectors.filter(s => s.securityLevel < 3).length / parkSectors.length * 100
    : 0;

Line Length

Maintaining a reasonable line length (usually 80-120 characters) helps with reading code without the need for horizontal scrolling:

// Line too long
const fullSecurityCheck = checkElectricFences() && checkMotionSensors() && checkCameraSystem() && checkRadioSystem() && staffMembersPresent >= minimumStaffRequired && weatherCondition !== 'storm';

// Split into easier to read parts
const fullSecurityCheck =
    checkElectricFences() &&
    checkMotionSensors() &&
    checkCameraSystem() &&
    checkRadioSystem() &&
    staffMembersPresent >= minimumStaffRequired &&
    weatherCondition !== 'storm';

Organizing code into logical groups improves its readability:

// Variable initialization
const parkName = "Jurassic Park";
const openingYear = 1993;
const isOpen = true;

// Enclosure status check
const fenceStatus = checkFences();
const dinoHealth = monitorDinoVitals();
const securityBreach = checkForBreaches();

// Reporting
generateStatusReport(fenceStatus, dinoHealth);
if (securityBreach) {
    alertSecurityTeam();
}

Code Formatting Tools

In modern JavaScript development, there are many tools that automate code formatting, similar to advanced monitoring systems in Jurassic Park that automate many security tasks:

  • Prettier - automatically formats code according to established rules
  • ESLint - checks code for errors and non-standard practices
  • EditorConfig - helps maintain consistent formatting across different editors and developers

Coding Standards and Styles

Just as Jurassic Park has its procedures and protocols, in the JavaScript world there are various recognized code style standards:

  • Airbnb JavaScript Style Guide - one of the most popular sets of rules
  • Google JavaScript Style Guide - used in Google projects
  • StandardJS - a minimalist no-configuration style

Practical Exercise

Look at the following unformatted code and think about how you could improve it using the principles you've learned:

// unformatted code
function trackDino(dinoId,name,   species,location){
// checks dinosaur position
let status='unknown';
if(location){status='tracked'}else{
    // dinosaur not found
    status='lost';
    triggerAlert(dinoId)
}
// save data to system
return{id:dinoId,name:name,species,
    status:status,lastSeen:location?new Date():null}}
// function call
const result=trackDino(42,'Blue','Velociraptor',{x:234,y:189});

Now compare it with the properly formatted version:

/**
 * Tracks a dinosaur's location and updates its status in the system
 * @param {number} dinoId - Dinosaur identifier
 * @param {string} name - Dinosaur name
 * @param {string} species - Dinosaur species
 * @param {Object|null} location - Location coordinates or null if not found
 * @returns {Object} Updated dinosaur data
 */
function trackDino(dinoId, name, species, location) {
    // Check dinosaur position
    let status = 'unknown';

    if (location) {
        status = 'tracked';
    } else {
        // Dinosaur not found - activate alarm procedure
        status = 'lost';
        triggerAlert(dinoId);
    }

    // Save data to the monitoring system
    return {
        id: dinoId,
        name: name,
        species,
        status: status,
        lastSeen: location ? new Date() : null
    };
}

// Tracking dinosaur "Blue"
const result = trackDino(42, 'Blue', 'Velociraptor', { x: 234, y: 189 });

Summary

Comments and code formatting in JavaScript, much like documentation and procedures in Jurassic Park, are essential for maintaining order, safety, and efficiency. Well-commented and formatted code:

  1. Is easier to understand by you and other developers
  2. Reduces the risk of errors and "escapes" (bugs)
  3. Makes it easier to maintain and develop the project in the future
  4. Improves team collaboration

Remember, just as in Jurassic Park, where neglect can lead to catastrophe (remember what happened when Dennis Nedry disabled the security systems?), neglected practices in code can lead to hard-to-detect bugs and maintenance problems.

In the following lessons, we will consistently apply these best practices, building increasingly advanced elements of our virtual Jurassic Park using JavaScript.

Code for this lesson: index.js
// Dinosaur Registry - Creating Objects
// Exercise: Creating and modifying JavaScript objects

// An object is a collection of properties (key: value)
const trex = {
  name: "Tyrannosaurus Rex",
  period: "Late Cretaceous",
  diet: "carnivorous",
  weight: 7000,
  isDangerous: true
};

console.log("=== T-Rex Profile ===");
console.log("Name:", trex.name);
console.log("Diet:", trex["diet"]);
console.log("Weight:", trex.weight, "kg");

// Adding a new property
trex.enclosure = "Sector A";
console.log("Enclosure:", trex.enclosure);

// Your task:
// 1. Create a raptor object with properties: name, speed, packSize, isAlpha
// 2. Display its properties
// 3. Add a new property

// Your code here:

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How does a single-line comment start in JavaScript?

  2. 2. Which naming convention is the standard for variables and functions in JavaScript?

Hands-on tasks in the game

  • Click in order

    Arrange the elements of a multi-line comment in JavaScript:

  1. QuestionSingle-line Comments
  2. QuestionNaming Conventions in JS
  3. Click in orderMulti-line Comment Syntax

Useful articles