JavaScript Style Guide: Writing Clean and Consistent Code

Здравствуйте, стремящиеся к кодированию! Я рад отправиться в это путешествие с вами, когда мы исследуем мир руководств по стилю JavaScript. Как кто-то, кто преподавал программирование на протяжении многих лет, я не могу сильнее подчеркнуть важность написания чистого, последовательного кода. Это как содержать свою комнату в чистоте - это делает все легче найти и управлять!

JavaScript - Style Guide

Why Do We Need a Style Guide? (Why Do We Need a Style Guide?)

Before we dive in, let's talk about why we even need a style guide. Imagine you're working on a group project, and everyone writes their code differently. It would be chaos! A style guide is like a set of rules that everyone agrees to follow, making the code easier to read and maintain.

Now, let's get into the nitty-gritty of JavaScript style guidelines!

Code Indentation (Code Indentation)

H3: The Foundation of Readable Code (The Foundation of Readable Code)

Indentation is like the foundation of a house – it's crucial for structure and stability. In JavaScript, we typically use spaces or tabs to indent our code. Let's look at an example:

function greetStudent(name) {
if (name) {
console.log("Hello, " + name + "!");
} else {
console.log("Hello, student!");
}
}

In this example, we've indented the code inside the function and the if-else statement. This makes it clear which parts of the code belong together.

Comments (Comments)

H3: Leaving Breadcrumbs for Future You (Leaving Breadcrumbs for Future You)

Comments are like little notes you leave for yourself (or others) in your code. They explain what the code does without affecting how it runs. Here's how we use them:

// This is a single-line comment

/*
This is a
multi-line comment
*/

/**
* This is a JSDoc comment
* It's used to document functions
* @param {string} name - The name of the student
*/
function greetStudent(name) {
// Code here
}

Remember, good comments explain why, not what. The code itself should be clear enough to show what it's doing.

Variable Declaration (Variable Declaration)

H3: Introducing Your Code's Cast of Characters (Introducing Your Code's Cast of Characters)

Variables are like the characters in your code's story. In JavaScript, we have a few ways to declare them:

// Using 'let' for variables that can change
let age = 25;

// Using 'const' for variables that won't change
const PI = 3.14159;

// Avoid using 'var' in modern JavaScript
// var oldWay = "We don't do this anymore";

Always declare your variables before using them, and try to use const unless you know the value will change.

Identifier Names in camelCase (Identifier Names in camelCase)

H3: Naming Conventions That Make Sense (Naming Conventions That Make Sense)

In JavaScript, we use camelCase for most of our identifiers. It's like squishing words together, but capitalizing each new word (except the first). Here's how it looks:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName;

function calculateArea(width, height) {
return width * height;
}

const MAX_SIZE = 100; // Exception: constants are often in ALL_CAPS

Spaces and Brackets (Spaces and Brackets)

H3: Giving Your Code Room to Breathe (Giving Your Code Room to Breathe)

Proper spacing makes your code easier to read. It's like adding paragraphs to a long essay. Let's see how we use spaces and brackets:

// Good spacing
if (condition) {
doSomething();
} else {
doSomethingElse();
}

// Function calls
console.log("Hello, World!");

// Arrays and objects
let colors = ["red", "green", "blue"];
let person = { name: "Alice", age: 30 };

Notice how we use spaces around operators and after commas. It's these little details that make your code look professional!

Object Rules (Object Rules)

H3: Structuring Your Data (Structuring Your Data)

Objects are like containers for related data. Here's how we typically structure them:

const student = {
name: "Bob",
age: 20,
grades: {
math: 90,
science: 85
},
isEnrolled: true
};

// Accessing object properties
console.log(student.name);
console.log(student["age"]);

Keep your object properties consistent and well-organized. It'll save you headaches later!

Statement Rules (Statement Rules)

H3: One Thought, One Line (One Thought, One Line)

In general, we try to keep each statement on its own line. It's like writing sentences in an essay – each one should express a complete thought:

let a = 5;
let b = 10;
let c = a + b;

if (c > 10) {
console.log("c is greater than 10");
}

This makes your code easier to read and debug.

Line Length (Line Length)

H3: Keeping Things Compact (Keeping Things Compact)

Try to keep your lines of code to a reasonable length – usually around 80-100 characters. If a line gets too long, break it up:

// Too long
let result = veryLongFunctionName(extremelyLongVariableName1, extremelyLongVariableName2, extremelyLongVariableName3);

// Better
let result = veryLongFunctionName(
extremelyLongVariableName1,
extremelyLongVariableName2,
extremelyLongVariableName3
);

This improves readability and makes your code look neater.

Putting It All Together (Putting It All Together)

Now that we've covered all these style guidelines, let's look at a complete example that puts everything into practice:

/**
* Calculates the total price of items in a shopping cart
* @param {Object[]} items - Array of items in the cart
* @returns {number} Total price
*/
function calculateTotalPrice(items) {
let total = 0;
const TAX_RATE = 0.08;

for (let i = 0; i < items.length; i++) {
let item = items[i];
let itemPrice = item.price * (1 + TAX_RATE);

total += itemPrice;

// Log each item's price with tax
console.log(`${item.name}: $${itemPrice.toFixed(2)}`);
}

return total.toFixed(2);
}

// Example usage
const shoppingCart = [
{ name: "T-shirt", price: 15.99 },
{ name: "Jeans", price: 39.99 },
{ name: "Shoes", price: 59.99 }
];

let finalPrice = calculateTotalPrice(shoppingCart);
console.log(`Total price: $${finalPrice}`);

This example showcases proper indentation, comments, variable declarations, camelCase naming, spacing, object usage, and adherence to line length guidelines.

Remember, following these style guidelines will make your code more readable and maintainable. It's a skill that will serve you well throughout your coding journey. Happy coding, and may your code always be clean and consistent! (Remember, following these style guidelines will make your code more readable and maintainable. It's a skill that will serve you well throughout your coding journey. Happy coding, and may your code always be clean and consistent!)

Method Description
calculateTotalPrice(items) Calculates the total price of items in a shopping cart, including tax
console.log() Outputs messages to the console for debugging and information display
toFixed(2) Formats a number to have two decimal places

Credits: Image by storyset