Best practices
Based on the knowledge so far, here are some basic habits for writing readable, maintainable code.
1. Naming conventions for variables and functions
// camelCase (variables and functions)
let firstName = "Taro";
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0);
}
// PascalCase (class names and constructor functions)
// Note: class itself is outside the scope of this guide. Here, just see it as an example of "what to write in PascalCase"
class UserProfile {
constructor(name) {
this.name = name;
}
}
// UPPER_SNAKE_CASE (constants)
const MAX_SIZE = 100;
const API_ENDPOINT = "https://api.example.com";
The goal of naming is to make "what it represents" and "how to use it" clear just by looking at the name. Unifying the case (format) for each kind of thing makes the kind of code obvious at a glance. Note that snake_case like user_name is not common in JavaScript.
2. Structuring code
Grouping related functionality into an object improves clarity.
// Group user-related functionality together
const userService = {
login(username, password) {
console.log(`${username} logged in`);
},
logout() {
console.log("Logged out");
},
getProfile(userId) {
return { id: userId, name: "Taro" };
}
};
userService.login("taro", "password");
console.log(userService.getProfile(1)); // { id: 1, name: 'Taro' }
3. Error handling
With try-catch, you can respond without stopping the processing even when an error occurs.
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
} catch (error) {
console.error("An error occurred:", error.message);
return null; // Return a default value
} finally {
console.log("Processing finished");
}
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // null (the error is caught)
When you don't use the error object, you can omit the parameter, as in catch {} (ES2019).
try {
riskyOperation();
} catch {
console.log("It failed, but processing continues");
}
4. Modularization (ES6)
Split functionality into separate files and reuse it with export / import.
// math.js
export function add(a, b) {
return a + b;
}
// Default export
export default function multiply(a, b) {
return a * b;
}
// app.js
import multiply, { add } from './math.js';
console.log(add(5, 3)); // 8
console.log(multiply(2, 6)); // 12
To load ES modules in the browser, you specify <script type="module">, and the import path needs to include the file extension, as in ./math.js. Node.js ES modules likewise require the extension; it can be omitted only when going through a bundler or with CommonJS require.
5. Debugging techniques
console has methods for different purposes.
console.log("Basic log output");
console.warn("Warning message");
console.error("Error message");
// Display data in table form
console.table([
{ name: "Suzuki", age: 30 },
{ name: "Sato", age: 25 }
]);
// Measure execution time
console.time("Processing time");
for (let i = 0; i < 1000000; i++) {
// Some processing
}
console.timeEnd("Processing time"); // Processing time: 1.234ms
Conclusion
In this guide, you learned the basic concepts and usage of JavaScript. Your understanding deepens by actually writing and trying out the code.
As your next step, we recommend moving on to the TypeScript Guide, which raises safety through types, and Clean Code, which raises code quality.