JavaScript and TypeScript course Β· Module 1: JavaScript Basics
Comments and Code Formatting
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.
1// This is a single-line comment
2let velociraptorCount = 3; // Number of Velociraptors in paddock BMulti-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.
1/*
2 This is a multi-line comment.
3 It can span several lines.
4 Safety protocol for the T-Rex enclosure:
5 1. Check fence power supply
6 2. Ensure all gates are closed
7 3. Monitor activity every 15 minutes
8*/
9
10let 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
1/**
2 * Calculates the safe distance from a dinosaur enclosure.
3 * @param {string} dinoType - The dinosaur species
4 * @param {number} dinoCount - Number of dinosaurs in the enclosure
5 * @param {boolean} isElectricFenceActive - Whether the electric fence is active
6 * @returns {number} Safe distance in meters
7 */
8function calculateSafeDistance(dinoType, dinoCount, isElectricFenceActive) {
9 // Function implementation...
10 return distance;
11}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
1// Velociraptor escape pattern prediction algorithm
2// Based on analysis of 10 previous escape attempts
3// and uses the behavior pattern described by Dr. Grant
4if ((attemptTime > sunsetTime && attemptTime < sunriseTime) &&
5 (weatherCondition === 'storm' || fencePowerLevel < 80)) {
6 // Elevated escape risk - activate additional security measures
7 activateSecondaryContainment();
8}3. Temporarily Disabling Code (Commenting Out)
1// Old feeding method - currently unused
2// function feedDinosaurs(dinoType) {
3// if (dinoType === 'herbivore') {
4// providePlants();
5// } else {
6// provideMeat();
7// }
8// }
9
10// New feeding method accounting for special diets
11function feedDinosaurs(dinoType, specialDiet) {
12 // Implementation accounting for special diets
13}4. TODO/FIXME/NOTE Markers
1// TODO: Add support for a new species in the feeding schedule
2// FIXME: Fix the bug in counting dinosaurs during rain
3// NOTE: The park API may change next monthSuch 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:
Write comments that explain "why," not "what"
1// BAD: 2// Increases the dinosaur count by 1 3dinoCount++; 4 5// GOOD: 6// Account for the newly hatched specimen from the laboratory 7dinoCount++;Keep comments up to date When you change code, also update the comments. Outdated comments are worse than no comments.
Use clear and precise language Just as in safety protocols, clarity is key.
What to Avoid:
Over-commenting
1// BAD: 2// Declaration of a variable with the number of dinosaurs 3let dinoCount = 15; 4 5// GOOD: (no comment needed, the code is self-documenting) 6let dinoCount = 15;Comments that obscure the code
1/* Warning! This code is complicated and only a senior can understand it. 2 Modify at your own risk! */Outdated comments
1// BAD: 2// Checks if there are 7 dinosaurs 3if (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:
1function checkParkSecurity() {
2 if (fencesActive) {
3 // Level 1 indentation
4 for (let sector of parkSectors) {
5 // Level 2 indentation
6 if (sector.hasCarnivores) {
7 // Level 3 indentation
8 runExtraChecks(sector);
9 }
10 }
11 } else {
12 // Level 1 indentation
13 activateEmergencyProtocol();
14 }
15}Curly Braces
There are two main styles for placing curly braces:
K&R Style (Kernighan & Ritchie)
1function checkFences() {
2 if (powerLevel < 50) {
3 sendAlert();
4 activateBackupGenerator();
5 } else {
6 logStatus("Fences operating correctly");
7 }
8}Allman Style
1function checkFences()
2{
3 if (powerLevel < 50)
4 {
5 sendAlert();
6 activateBackupGenerator();
7 }
8 else
9 {
10 logStatus("Fences operating correctly");
11 }
12}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:
1// camelCase for variables and functions
2let velociraptorCount = 3;
3function checkSecuritySystems() { }
4
5// PascalCase for classes and constructors
6class DinosaurPaddock { }
7
8// UPPER_CASE for constants
9const MAX_VISITORS_PER_TOUR = 8;
10const PARK_OPENING_HOURS = {
11 start: 8,
12 end: 20
13};Spaces Around Operators
For improved readability, it's worth using spaces around operators:
1// Hard to read
2let safetyRating=parkSectors.length>0?parkSectors.filter(s=>s.securityLevel<3).length/parkSectors.length*100:0;
3
4// Easier to read
5let safetyRating = parkSectors.length > 0
6 ? parkSectors.filter(s => s.securityLevel < 3).length / parkSectors.length * 100
7 : 0;Line Length
Maintaining a reasonable line length (usually 80-120 characters) helps with reading code without the need for horizontal scrolling:
1// Line too long
2const fullSecurityCheck = checkElectricFences() && checkMotionSensors() && checkCameraSystem() && checkRadioSystem() && staffMembersPresent >= minimumStaffRequired && weatherCondition !== 'storm';
3
4// Split into easier to read parts
5const fullSecurityCheck =
6 checkElectricFences() &&
7 checkMotionSensors() &&
8 checkCameraSystem() &&
9 checkRadioSystem() &&
10 staffMembersPresent >= minimumStaffRequired &&
11 weatherCondition !== 'storm';Grouping Related Code
Organizing code into logical groups improves its readability:
1// Variable initialization
2const parkName = "Jurassic Park";
3const openingYear = 1993;
4const isOpen = true;
5
6// Enclosure status check
7const fenceStatus = checkFences();
8const dinoHealth = monitorDinoVitals();
9const securityBreach = checkForBreaches();
10
11// Reporting
12generateStatusReport(fenceStatus, dinoHealth);
13if (securityBreach) {
14 alertSecurityTeam();
15}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:
1// unformatted code
2function trackDino(dinoId,name, species,location){
3// checks dinosaur position
4let status='unknown';
5if(location){status='tracked'}else{
6 // dinosaur not found
7 status='lost';
8 triggerAlert(dinoId)
9}
10// save data to system
11return{id:dinoId,name:name,species,
12 status:status,lastSeen:location?new Date():null}}
13// function call
14const result=trackDino(42,'Blue','Velociraptor',{x:234,y:189});Now compare it with the properly formatted version:
1/**
2 * Tracks a dinosaur's location and updates its status in the system
3 * @param {number} dinoId - Dinosaur identifier
4 * @param {string} name - Dinosaur name
5 * @param {string} species - Dinosaur species
6 * @param {Object|null} location - Location coordinates or null if not found
7 * @returns {Object} Updated dinosaur data
8 */
9function trackDino(dinoId, name, species, location) {
10 // Check dinosaur position
11 let status = 'unknown';
12
13 if (location) {
14 status = 'tracked';
15 } else {
16 // Dinosaur not found - activate alarm procedure
17 status = 'lost';
18 triggerAlert(dinoId);
19 }
20
21 // Save data to the monitoring system
22 return {
23 id: dinoId,
24 name: name,
25 species,
26 status: status,
27 lastSeen: location ? new Date() : null
28 };
29}
30
31// Tracking dinosaur "Blue"
32const 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:
- Is easier to understand by you and other developers
- Reduces the risk of errors and "escapes" (bugs)
- Makes it easier to maintain and develop the project in the future
- 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
1// Dinosaur Registry - Creating Objects
2// Exercise: Creating and modifying JavaScript objects
3
4// An object is a collection of properties (key: value)
5const trex = {
6 name: "Tyrannosaurus Rex",
7 period: "Late Cretaceous",
8 diet: "carnivorous",
9 weight: 7000,
10 isDangerous: true
11};
12
13console.log("=== T-Rex Profile ===");
14console.log("Name:", trex.name);
15console.log("Diet:", trex["diet"]);
16console.log("Weight:", trex.weight, "kg");
17
18// Adding a new property
19trex.enclosure = "Sector A";
20console.log("Enclosure:", trex.enclosure);
21
22// Your task:
23// 1. Create a raptor object with properties: name, speed, packSize, isAlpha
24// 2. Display its properties
25// 3. Add a new property
26
27// Your code here:
28Spotted 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. How does a single-line comment start in JavaScript?
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: