JavaScript Style Guide

A consistent coding style makes code easier to read, maintain, and collaborate on. This guide covers the most widely adopted JavaScript conventions based on popular style guides like Airbnb, Google, and StandardJS.

Naming Conventions

Choosing the right naming convention communicates intent. JavaScript uses different casing styles for different kinds of identifiers.

Naming Conventions
// camelCase — variables, functions, methods
const firstName = 'Alice';
const itemCount = 42;
function getUserName() {
  return 'Alice';
}
console.log(getUserName()); // 'Alice'

// PascalCase — classes, constructors, components
class UserProfile {
  constructor(name) {
    this.name = name;
  }
}
const user = new UserProfile('Bob');
console.log(user.name); // 'Bob'

// UPPER_SNAKE_CASE — constants
const MAX_RETRIES = 3;
const API_BASE_URL = 'https://api.example.com';
console.log(MAX_RETRIES); // 3

// _ prefix — private by convention (not enforced)
class Counter {
  _count = 0;
  increment() { this._count++; }
  getCount() { return this._count; }
}
const c = new Counter();
c.increment();
console.log(c.getCount()); // 1
ConventionUsed ForExample
camelCaseVariables, functions, methodsuserName, getTotal()
PascalCaseClasses, constructors, React componentsUserProfile, EventEmitter
UPPER_SNAKE_CASEConstants, config valuesMAX_SIZE, API_KEY
_prefixPrivate members (convention)_internalState
#prefixPrivate class fields (ES2022)#count

Indentation and Formatting

Consistent indentation and formatting is crucial for readability. Most teams use either 2 spaces or 4 spaces for indentation. Tabs vs. spaces is a preference, but be consistent.

Indentation and Braces
// 2-space indentation (most common in JS)
function greet(name) {
  if (name) {
    console.log(`Hello, ${name}!`);
  } else {
    console.log('Hello, stranger!');
  }
}
greet('Alice'); // Hello, Alice!

// Always use braces, even for single-line blocks
// Good
if (true) {
  console.log('always use braces');
}

// Avoid: no braces
// if (true) console.log('risky');

// Line length: stay under 80-100 characters
// Break long lines at logical points
const message =
  'This is a very long string that ' +
  'should be broken across lines';
console.log(message);

Semicolons and Quotes

While JavaScript has Automatic Semicolon Insertion (ASI), most style guides recommend always using semicolons to avoid edge cases. For strings, pick single quotes or template literals and be consistent.

Semicolons and Quotes
// Always use semicolons (recommended)
const name = 'Alice';
const age = 30;

// Prefer single quotes for simple strings
const greeting = 'Hello, World!';
console.log(greeting);

// Use template literals for interpolation
const message = `Hello, ${name}! You are ${age}.`;
console.log(message); // Hello, Alice! You are 30.

// Use double quotes only for strings containing single quotes
const text = "It's a beautiful day";
console.log(text);

// Or escape the single quote
const text2 = 'It\'s a beautiful day';
console.log(text2);

Variable Declarations

Modern JavaScript has three ways to declare variables: const, let, and var. The best practice is to prefer const, use let when reassignment is needed, and avoid var.

Variable Declaration Best Practices
// Prefer const for values that won't be reassigned
const PI = 3.14159;
const user = { name: 'Alice' };
user.name = 'Bob'; // OK — object is mutable, reference is const
console.log(user.name); // 'Bob'

// Use let only when you need to reassign
let count = 0;
count += 1;
console.log(count); // 1

// Avoid var — it has function scope and hoisting issues
// var x = 10; // Don't use this

// Declare one variable per statement
const firstName = 'Alice';
const lastName = 'Smith';
console.log(firstName, lastName); // Alice Smith

// Group const and let declarations
const a = 1;
const b = 2;
let c = 3;
let d = 4;
console.log(a + b + c + d); // 10

Function Style

Use function declarations for named functions and arrow functions for callbacks and short inline functions. Be consistent within your codebase.

Function Style Conventions
// Function declarations for named, reusable functions
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// Arrow functions for callbacks
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// Arrow functions for short expressions
const add = (a, b) => a + b;
console.log(add(3, 4)); // 7

// Use default parameters
function greet(name = 'World') {
  console.log(`Hello, ${name}!`);
}
greet();        // Hello, World!
greet('Alice'); // Hello, Alice!

// Return early to avoid deep nesting
function processUser(user) {
  if (!user) return null;
  if (!user.name) return null;
  return `User: ${user.name}`;
}
console.log(processUser({ name: 'Bob' })); // 'User: Bob'
console.log(processUser(null)); // null
📝 Note: Use a linter like ESLint to automatically enforce style rules. Popular configs include eslint-config-airbnb, eslint-config-standard, and eslint-config-prettier.
Exercise:
Which naming convention should be used for JavaScript class names?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.