Skip to main content

JavaScript Code Style

Introduction

Code style is an essential aspect of writing JavaScript that's often overlooked by beginners. While your code may work correctly with any style, following consistent conventions makes your code more readable, maintainable, and professional. Good code style reduces bugs, improves collaboration, and makes it easier for others (including your future self) to understand your code.

In this guide, we'll explore JavaScript code style best practices that will help you write cleaner, more professional code.

Why Code Style Matters

Before diving into specific guidelines, it's important to understand why code style matters:

  1. Readability - Well-styled code is easier to read and understand
  2. Maintainability - Consistent code is easier to modify and debug
  3. Collaboration - Teams work more efficiently with a shared style guide
  4. Professionalism - Clean code demonstrates attention to detail and craftsmanship

Basic Formatting Rules

Indentation

Use consistent indentation throughout your code. The standard is either 2 or 4 spaces (with 2 spaces being increasingly common in JavaScript).

javascript
// Good (2-space indentation)
function calculateArea(width, height) {
const area = width * height;
return area;
}

// Avoid (inconsistent indentation)
function calculateArea(width, height) {
const area = width * height;
return area;
}

Semicolons

JavaScript allows optional semicolons, but including them at the end of statements is recommended to avoid potential issues.

javascript
// Good
let name = 'John';
console.log(name);

// Avoid (no semicolons)
let name = 'John'
console.log(name)

Line Length

Keep lines of code at a reasonable length (typically 80-100 characters). This improves readability, especially when viewing code in editors side-by-side.

javascript
// Good
const longMessage =
'This is a very long message that would exceed our preferred line length, ' +
'so we break it into multiple lines.';

// Avoid
const longMessage = 'This is a very long message that would exceed our preferred line length, so we break it into multiple lines.';

Naming Conventions

Variables and Functions

Use camelCase for variables and functions:

javascript
// Good
const firstName = 'John';
function calculateTotalPrice(items) {
// function implementation
}

// Avoid
const first_name = 'John';
function calculate_total_price(items) {
// function implementation
}

Classes

Use PascalCase for class names:

javascript
// Good
class UserProfile {
constructor(user) {
this.user = user;
}
}

// Avoid
class userProfile {
constructor(user) {
this.user = user;
}
}

Constants

Use UPPER_SNAKE_CASE for constants that are truly immutable and represent fixed values:

javascript
// Good
const MAX_USERS = 50;
const API_BASE_URL = 'https://api.example.com';

// Regular variables (even if const) use camelCase
const userPreferences = {
theme: 'dark',
notifications: true
};

Spacing

Operators

Place spaces around operators for improved readability:

javascript
// Good
let sum = a + b;
let name = firstName + ' ' + lastName;

// Avoid
let sum=a+b;
let name=firstName+' '+lastName;

Function Calls

No spaces between function name and parentheses, but space after commas in parameter lists:

javascript
// Good
console.log('Hello');
calculateArea(10, 20);

// Avoid
console.log ('Hello');
calculateArea(10,20);

Object Literals and Arrays

Use spaces after colons and commas:

javascript
// Good
const user = {
name: 'John',
age: 30,
hobbies: ['reading', 'swimming', 'coding']
};

// Avoid
const user = {
name:'John',
age:30,
hobbies:['reading','swimming','coding']
};

Code Blocks and Braces

Brace Style

Use the "one true brace style" (1TBS) where opening braces go on the same line:

javascript
// Good
if (condition) {
// code
} else {
// code
}

function doSomething() {
// code
}

// Avoid
if (condition)
{
// code
}
else
{
// code
}

Blocks in Control Statements

Always use braces for blocks in control statements, even for single-line blocks:

javascript
// Good
if (condition) {
doSomething();
}

// Avoid (omitting braces)
if (condition)
doSomething();

Comments

Single-Line Comments

Use single-line comments for brief explanations:

javascript
// Calculate the total price including tax
const totalPrice = subtotal * (1 + taxRate);

Multi-Line Comments

Use multi-line comments for more detailed explanations:

javascript
/**
* Calculates the monthly payment for a loan.
* Formula: P * (r * (1 + r)^n) / ((1 + r)^n - 1)
* Where:
* P = principal
* r = monthly interest rate
* n = number of payments
*/
function calculateMonthlyPayment(principal, annualRate, years) {
// implementation
}

JSDoc Comments

For functions, especially those in libraries or APIs, consider using JSDoc style comments:

javascript
/**
* Calculates the area of a rectangle.
* @param {number} width - The width of the rectangle
* @param {number} height - The height of the rectangle
* @returns {number} The area of the rectangle
*/
function calculateArea(width, height) {
return width * height;
}

Real-World Examples

Before: Poorly Styled Code

javascript
function find_user(users,id){
var foundUser=null;
for(var i=0;i<users.length;i++){
if(users[i].id===id){foundUser=users[i];break;}
}
return foundUser;
}

var result=find_user([{id:1,name:"John"},{id:2,name:"Jane"}],2)
console.log(result)

After: Well-Styled Code

javascript
/**
* Finds a user by their ID
* @param {Array} users - Array of user objects
* @param {number} id - The ID to search for
* @returns {Object|null} The found user or null
*/
function findUser(users, id) {
let foundUser = null;

for (let i = 0; i < users.length; i++) {
if (users[i].id === id) {
foundUser = users[i];
break;
}
}

return foundUser;
}

const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];

const result = findUser(users, 2);
console.log(result); // Output: { id: 2, name: "Jane" }

Tools for Enforcing Code Style

Several tools can help you maintain consistent code style:

ESLint

ESLint is a static code analysis tool that identifies problematic patterns and enforces style rules:

bash
# Install ESLint
npm install eslint --save-dev

# Initialize ESLint configuration
npx eslint --init

Example ESLint configuration (.eslintrc.js):

javascript
module.exports = {
"env": {
"browser": true,
"es2021": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
"indent": ["error", 2],
"semi": ["error", "always"],
"quotes": ["error", "single"]
}
};

Prettier

Prettier is an opinionated code formatter that automatically formats your code:

bash
# Install Prettier
npm install --save-dev prettier

Example Prettier configuration (.prettierrc):

json
{
"singleQuote": true,
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"printWidth": 80
}

Several established style guides offer comprehensive guidelines for JavaScript:

  1. Airbnb JavaScript Style Guide - One of the most popular style guides
  2. Google JavaScript Style Guide - Style guide used by Google
  3. StandardJS - A simpler "zero-configuration" style guide

Best Practices

  1. Be consistent - Follow the same rules throughout your codebase
  2. Use a style guide - Adopt an existing style guide rather than creating your own
  3. Automate enforcement - Use tools like ESLint and Prettier to automatically check and format code
  4. Configure your editor - Set up your code editor to help maintain your style rules
  5. Review your code - Regularly review your code for style issues

Summary

Consistent JavaScript code style is crucial for writing maintainable and professional code. Following established conventions for indentation, naming, spacing, and comments significantly improves your code's readability and makes collaboration easier.

Remember that while there's no universally "correct" style, consistency within your project or team is vital. Using tools like ESLint and Prettier can help enforce your chosen style automatically.

Additional Resources

  1. Airbnb JavaScript Style Guide
  2. Google JavaScript Style Guide
  3. StandardJS
  4. ESLint Documentation
  5. Prettier Documentation

Exercises

  1. Take a poorly formatted JavaScript file and reformat it according to the guidelines in this article.
  2. Set up ESLint and Prettier in a project and configure them to enforce a consistent style.
  3. Create a small style guide for a team project, specifying your choices for indentation, naming conventions, and other style rules.
  4. Review open-source JavaScript code to identify different style approaches and note which ones you find most readable.


If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)