JavaScript Coding Guidelines
Build cleaner, more maintainable JavaScript by following practical standards used in real-world teams.
These guidelines are practical recommendations for writing JavaScript that is easier to read, maintain, and review.
Names should reveal what a value or function represents. Follow the same convention throughout a project. Descriptive names make code easier to review and reduce guesswork.
Choose descriptive names
Avoid
const x = 25;
class car {}
function calc(a, b) { return a + b; }Prefer
const userAge = 25;
class CarModel {}
function calculateTotalPrice(price, tax) {
return price + tax;
}Use lowerCamelCase for variables and functions, and PascalCase (UpperCamelCase) for classes.
Name shared fixed values consistently
Avoid
const maxretryattempts = 3;
const taxrate = 0.18;Prefer
const MAX_RETRY_ATTEMPTS = 3;
const TAX_RATE = 0.18;
const totalPrice = 500;UPPER_SNAKE_CASE is a common convention for shared fixed configuration. Local constants usually use lowerCamelCase.
Learn more: Variables and identifiers
Give functions a clear purpose and descriptive names. Extract repeated behavior when it makes the code easier to understand. This avoids duplicated logic and keeps later changes consistent.
Reuse a calculation
Avoid
console.log(10 * 2);
console.log(20 * 2);
console.log(30 * 2);Prefer
const double = number => number * 2;
console.log(double(10));
console.log(double(20));
console.log(double(30));A named function keeps the calculation in one place. Both versions print the same results.
Learn more: Functions
Choose declarations according to whether the binding needs to be reassigned. Choosing deliberately makes reassignment and mutation easier to reason about.
Prefer const for a stable binding
Avoid
var userName = "John";
console.log(userName);Prefer
const userName = "John";
console.log(userName);Use const by default and let for reassignment. var is valid JavaScript, but its function scope and hoisting can be surprising.
Learn more: Variables and identifiers
Write statements in a consistent, easy-to-scan style. JavaScript permits several styles, so agree on one with your team. Clear blocks make control flow easier to extend without changing its meaning.
Make branches easy to read
Avoid
const isReady = true;
if (isReady) console.log("Ready");Prefer
const isReady = true;
if (isReady) {
console.log("Ready");
}Braces make the intended scope of each branch clear, especially when another statement is added.
Read the error message and location first. Fix the cause instead of suppressing the message. Checking input at a boundary prevents invalid values from producing misleading results.
Validate a number before using it
Avoid
function double(value) {
return value * 2;
}
console.log(double("hello"));Prefer
function double(value) {
if (!Number.isFinite(value)) {
throw new TypeError("Expected a finite number");
}
return value * 2;
}
console.log(double(4));Number.isFinite rejects NaN and infinities as well as non-number values. An explicit error points to the problem.
Learn more: Understanding errors
Warnings identify possible problems, not necessarily failures. Investigate them before deciding whether a change is needed. Separating actionable warnings from intentional exceptions keeps useful diagnostics visible.
Remove unused values
Avoid
const price = 20;
const unusedDiscount = 5;
console.log(price);Prefer
const price = 20;
console.log(price);Unused declarations make it harder to see which data matters. A linter can flag them during development.
A formatter handles layout; a linter can flag suspicious code. Use the configuration agreed by your project. Consistent layout reduces visual noise so behavior changes stand out in reviews.
Use consistent spacing
Avoid
function total(a,b){return a+b;}
console.log(total(2,3));Prefer
function total(a, b) {
return a + b;
}
console.log(total(2, 3));Formatting does not change the result, but consistent indentation and spacing make a function easier to scan.
Keep values in the smallest scope that needs them. This reduces accidental changes and naming conflicts. Narrow scopes limit where values can be changed or collide.
Keep temporary values local
Avoid
let total;
function printTotal() {
total = 10 + 5;
console.log(total);
}
printTotal();Prefer
function printTotal() {
const total = 10 + 5;
console.log(total);
}
printTotal();The second total is available only inside the function. Both examples print the same value.
Learn more: JavaScript scope
Use names to explain what code does, and comments to explain a useful reason or constraint that the code cannot show. Useful context helps maintainers preserve intent when requirements change.
Explain why, not the obvious
Avoid
// Set the retry delay to 1000.
const retryDelayMs = 1000;
console.log(retryDelayMs);Prefer
// Leave time for the service to recover between retries.
const retryDelayMs = 1000;
console.log(retryDelayMs);The comment adds context instead of repeating the assignment.
Use the project's existing tools to catch mistakes, and test important behavior including edge cases. Edge cases reveal assumptions that a typical example alone can miss.
Check a boundary as well as a typical value
Avoid
function isAdult(age) { return age >= 18; }
console.assert(isAdult(25));Prefer
function isAdult(age) { return age >= 18; }
console.assert(isAdult(18));
console.assert(!isAdult(17));A small assertion catches a regression that a single happy-path check could miss.
Make decisions explicit and keep branches shallow when that improves readability. Shallow control flow helps readers identify the main path.
Return early for an invalid case
Avoid
function greeting(name) {
if (name) {
return "Hello, " + name;
} else {
return "Name required";
}
}
console.log(greeting("Ana"));Prefer
function greeting(name) {
if (!name) return "Name required";
return "Hello, " + name;
}
console.log(greeting("Ana"));Both functions return the same messages. The early return leaves the main path less nested.
Write code for the next person who will read it. Prefer clear, predictable behavior over clever shortcuts. Explicit ownership helps avoid side effects that surprise callers.
Avoid changing data owned by a caller
Avoid
const scores = [8, 2, 5];
const sorted = scores.sort((a, b) => a - b);
console.log(scores); // Also changedPrefer
const scores = [8, 2, 5];
const sorted = [...scores].sort((a, b) => a - b);
console.log(sorted, scores);sort changes the original array. Copy it first when the caller still needs the original order.
Learn more: Arrays
Group related files so people can find them. A small project can stay simple; adapt the structure as it grows. A clear layout lowers the effort of finding code as the project grows.
Group files by responsibility
Avoid
src/
app.js
button.js
date.js
form.jsPrefer
src/
app.js
components/
button.js
form.js
utils/
date.jsThe preferred example makes related interface and utility files easier to locate. This is one possible structure, not a JavaScript requirement.
Make conversions and comparisons intentional, especially when input comes from a form or URL. Explicit conversions avoid relying on coercion or truthiness that may not match the input's meaning.
Convert input before comparing
Avoid
const input = "18";
console.log(input == 18); // Coerces the stringPrefer
const input = "18";
const age = Number(input);
console.log(Number.isFinite(age) && age === 18);Strict equality does not coerce types. Convert input deliberately and check that it is valid before using it.
Preserve meaningful zero values
Avoid
const settings = { volume: 0 };
const volume = settings.volume || 50;
console.log(volume); // 50, not 0Prefer
const settings = { volume: 0 };
const volume = settings?.volume ?? 50;
console.log(volume); // 0Use ?? when only null or undefined should trigger a fallback. Unlike ||, it keeps 0, false, and an empty string.
Compare approaches by the problem they solve. The goal is maintainability, not treating every alternative as invalid. A comparison is useful only when both examples' behavior and tradeoffs are clear.
Name an important condition
Avoid
const age = 20;
const hasTicket = true;
if (age >= 18 && hasTicket) console.log("Enter");Prefer
const age = 20;
const hasTicket = true;
const canEnter = age >= 18 && hasTicket;
if (canEnter) console.log("Enter");A named condition makes the decision easier to understand. Both examples use the same test.
For an interview, explain your assumptions, choose clear names, and check a typical case and an edge case. Explaining your reasoning and boundaries shows how you approach unfamiliar problems.
Explain behavior with meaningful names
Avoid
function f(a) { return a.length === 0; }
console.log(f([]));Prefer
function isEmpty(items) {
return items.length === 0;
}
console.log(isEmpty([])); // true
console.log(isEmpty([1])); // falseA descriptive name and boundary checks communicate the intended behavior without relying on a particular coding style.
Wait for a result when later work depends on it. Independent operations may run concurrently when that is safe. Running independent work together can reduce latency, while dependency order still matters.
Start independent work together
Avoid
const delay = value => new Promise(resolve => setTimeout(() => resolve(value), 100));
async function showValues() {
const first = await delay(1);
const second = await delay(2);
return [first, second];
}
showValues().then(console.log);Prefer
const delay = value => new Promise(resolve => setTimeout(() => resolve(value), 100));
async function getValues() {
const first = delay(1);
const second = delay(2);
return Promise.all([first, second]);
}
getValues().then(console.log);Promise.all fulfills when both operations succeed and rejects as soon as one rejects; it does not cancel the other work. Use it only when operations are independent.
Learn more: Async and await
Keep DOM updates clear and treat user-provided text as text rather than HTML. This distinction helps keep user-controlled text from being interpreted as markup.
Use textContent for plain text
Avoid
const message = "<b>Hello</b>";
const output = document.createElement("p");
output.innerHTML = message;
document.body.append(output);Prefer
const message = "<b>Hello</b>";
const output = document.createElement("p");
output.textContent = message;
document.body.append(output);textContent displays text without parsing it as markup. Use HTML insertion only when markup is intended and safely handled.
Learn more: DOM tutorial
Handle errors where you can add context or recover. Otherwise let the caller decide what to do. Swallowing a failure hides it; context or propagation lets the right layer respond.
Do not silently discard a parsing failure
Avoid
try {
JSON.parse("{");
} catch (error) {
// Nothing happens.
}Prefer
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (error) {
throw new Error("Settings must contain valid JSON: " + error.message);
}
}
parseSettings("{");The wrapper adds context and propagates the failure so a caller can handle it.
Learn more: Error handling
Treat input from users and the browser as untrusted. Validate and authorize on the server, even when the browser also validates. Browser-side checks improve feedback but cannot enforce authorization or protect secrets.
Parse data instead of executing it
Avoid
const userInput = "42"; // Assume this value came from an untrusted source.
const amount = eval(userInput);
console.log(amount);Prefer
const userInput = "42";
const amount = Number(userInput);
if (Number.isFinite(amount)) {
console.log(amount);
}eval interprets its input as JavaScript, so untrusted input can run arbitrary code in that context. Parse the expected value and validate it instead.
Measure a real bottleneck before optimizing. Prefer a simple solution until the data shows a need for change. Measurements help target optimizations that affect users without adding needless complexity.
Avoid repeating invariant work
Avoid
const names = ["Ana", "Lee"];
const query = "A";
const matches = names.filter(name =>
name.toLowerCase().includes(query.toLowerCase())
);
console.log(matches);Prefer
const names = ["Ana", "Lee"];
const query = "A";
const normalizedQuery = query.toLowerCase();
const matches = names.filter(name =>
name.toLowerCase().includes(normalizedQuery)
);
console.log(matches);The normalized search term is the same for every item, so it can be prepared once. Measure larger changes in the real application.
They are shared practices for writing readable, maintainable code. They help a team make consistent choices without replacing judgment.
Standards often cover broader team practices; a style guide usually focuses on conventions such as naming and formatting. Teams may use the terms differently.
Shared conventions make code easier to read and review, so a team can focus on behavior and design.
Examples include relying on accidental type coercion, ignoring errors, and changing shared data unexpectedly. Use clear conversions, useful error handling, and focused tests.
Practice explaining your choices, use meaningful names, and test normal and edge cases. A convention is not necessarily a language rule.