You will apply JavaScript habits that reduce bugs and make code easier to read by using const, strict equality, small pure functions, and clear error handling.
What it is
JavaScript best practices are small, repeatable coding habits that make programs safer, clearer, and easier to maintain. The mental model is simple: write code for the next reader, not just for the computer. A good JavaScript file states intent early, avoids surprising type conversions, keeps functions small, and handles failure paths explicitly.
Related terms include immutability, pure function, strict equality, module, and linting. These are not just style rules; they reduce the number of ways code can behave unexpectedly.
Why it matters
- Using
constprevents accidental reassignment and makes variable intent clearer. - Using
===avoids loose equality surprises such as0 == "". - Small pure functions are easier to test, reuse, and reason about.
- Early returns reduce deep nesting and make invalid input handling obvious.
- Explicit async error handling prevents silent failures in promises.
Syntax or steps
- Declare variables with
constunless the binding must change. - Use
letonly for values that are reassigned, such as loop counters. - Compare values with
===and!==instead of==and!=. - Extract repeated logic into small functions that do one job.
- Handle async work with
tryandcatch, or attach acatchto a promise chain.
Example
const MIN_AGE = 18;
function canVote(age) {
if (typeof age !== "number" || Number.isNaN(age)) {
return false;
}
return age >= MIN_AGE;
}
function formatMessage(age) {
if (!canVote(age)) {
return "Not eligible to vote.";
}
return "Eligible to vote.";
}
console.log(formatMessage(20));
console.log(formatMessage("20"));
This example uses a named constant, a small validation function, and a formatting function. canVote is predictable: it checks the type, rejects NaN, and compares with >=. formatMessage does not repeat the rule; it asks canVote and returns a message. The second call logs "Not eligible to vote." because a string is not a number, which avoids the loose equality trap of treating "20" as valid.
Common mistakes
- Using
varin new code. Fix: useconstby default andletonly when needed. - Using
==because it is shorter. Fix: use===unless you have a specific, reviewed reason not to. - Writing one large function that validates, calculates, formats, and saves data. Fix: split it into smaller functions with clear names.
- Calling an async function without handling rejection. Fix: use
tryandcatchorpromise.catch().
When to use it
These practices are appropriate for almost all JavaScript code. The closest comparison is choosing between const, let, and var.
| Choice | Use when | Avoid when |
|---|---|---|
const | The variable binding should not be reassigned. | You need to change the binding later. |
let | You need a mutable binding, such as a loop counter. | It is only being used as a default habit. |
var | You are maintaining legacy code that already depends on its behavior. | You are writing new code. |
Practice
Guided exercise: Write a function named calculateShipping that takes a weight in kilograms. Use const for rates, reject non-number input, and return 0 for free shipping over 50. Expected output: calculateShipping(10) returns a number, and calculateShipping("10") returns 0 or an error message if you choose to validate strictly.
Challenge: Write an async function named loadUser that calls fetch("/api/user"), checks response.ok, parses JSON, and catches errors. Hint: use try, await, and catch.
Quick check
Question: Why is const usually preferred over let?
Answer: const makes it clear that the variable binding will not be reassigned, which reduces accidental changes and helps readers understand the code faster.
Summary
JavaScript best practices are habits that make intent explicit and failure visible. Prefer const, strict equality, small pure functions, and clear async error handling. These choices do not make code fancy; they make it safer and easier to maintain.