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 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.
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 (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"];Comments in JavaScript serve various purposes, similar to different types of documentation in Jurassic Park:
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.
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}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}1// // FIXME: Fix the bug in counting dinosaurs during rain
2// NOTE: The park API may change next monthSuch markers are often highlighted by code editors and can be easily found when working on code.
Just as in Jurassic Park, where outdated or misleading information can be dangerous, in code, poor commenting practices can lead to problems:
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.
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 outdatedJust as precise maps and plans of Jurassic Park are essential for effective management, proper JavaScript code formatting is crucial for readability and maintenance.
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}There are two main styles for placing curly braces:
1function checkFences() {
2 if (powerLevel < 50) {
3 sendAlert();
4 activateBackupGenerator();
5 } else {
6 logStatus("Fences operating correctly");
7 }
8}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.
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};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;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';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}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:
Just as Jurassic Park has its procedures and protocols, in the JavaScript world there are various recognized code style standards:
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 });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:
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.