Skip to content

JavaScript Do's and Don'ts

This lesson explains JavaScript Do's and Don'ts in JavaScript with beginner-friendly examples, practical use cases, and clear best practices.

JavaScript Do's and Don'ts Overview

JavaScript do's and don'ts are practical coding guidelines that help developers write clean, secure, readable, and maintainable JavaScript. They cover variables, functions, arrays, objects, DOM manipulation, events, asynchronous programming, storage, performance, security, and debugging.

Following JavaScript do's and avoiding common don'ts helps reduce bugs, prevent security issues, improve performance, and make code easier for teams to understand. These guidelines are useful for beginners, frontend developers, full-stack developers, interview preparation, and real-world production projects.

JavaScript Do's and Don'ts Example

const users = [
  { name: "John", active: true },
  { name: "Sarah", active: false }
];

function getActiveUsers(userList) {
  return userList.filter(function(user) {
    return user.active === true;
  });
}

// Do: use clear names, const, strict equality, and small functions

const activeUsers = getActiveUsers(users);

console.log(activeUsers);

// Don't: use unclear names, loose equality, or global side effects

This example follows important JavaScript do's: clear variable names, const, strict equality, focused functions, and predictable return values.

50 JavaScript Do's and Don'ts with Examples

The following table summarizes important JavaScript coding rules with practical examples and safer alternatives.

# Do Don't Recommended Syntax
1Use const by default.Do not use var for modern code.const name = "John";
2Use let when reassignment is needed.Do not reassign const variables.let count = 0; count = count + 1;
3Use strict equality.Do not rely on loose equality.if (age === 18) { allowAccess(); }
4Use descriptive variable names.Do not use unclear names like x or data1.const totalPrice = price + tax;
5Use camelCase for variables and functions.Do not mix naming styles randomly.const userName = "John";
6Use PascalCase for classes.Do not name classes like regular variables.class UserProfile { }
7Keep functions small.Do not write large functions that do many things.function add(a, b) { return a + b; }
8Write functions with one responsibility.Do not mix validation, formatting, and API logic in one function.function validateEmail(email) { return email.includes("@"); }
9Return values from functions.Do not rely on unnecessary global mutations.function getTotal(a, b) { return a + b; }
10Use default parameters.Do not allow avoidable undefined arguments.function greet(name = "Guest") { return name; }
11Use modules for reusable code.Do not put all logic in one file.import { formatDate } from "./utils.js";
12Use named exports for utilities.Do not overuse default exports for many helpers.export function formatDate(date) { return date; }
13Use destructuring when it improves readability.Do not overuse deeply nested destructuring.const { name, email } = user;
14Use spread syntax for immutable updates.Do not mutate objects unexpectedly.const updatedUser = { ...user, active: true };
15Use array methods for clear data operations.Do not use complex loops when methods are clearer.const names = users.map(user => user.name);
16Use filter() for selection.Do not use map() for filtering.const active = users.filter(user => user.active);
17Use find() for one matching item.Do not use filter() when only one result is needed.const user = users.find(user => user.id === 1);
18Use reduce() for totals.Do not make reduce logic hard to read.const total = prices.reduce((sum, price) => sum + price, 0);
19Provide an initial value to reduce().Do not assume arrays always contain data.items.reduce((total, item) => total + item.price, 0);
20Use optional chaining for nested data.Do not create long unsafe property chains.const city = user.address?.city;
21Use nullish coalescing for precise fallbacks.Do not use || when 0 or empty string are valid.const limit = settings.limit ?? 10;
22Handle errors with try...catch.Do not let risky code crash silently.try { runTask(); } catch (error) { console.log(error.message); }
23Use finally for cleanup.Do not leave loading states active after failures.try { load(); } finally { hideLoader(); }
24Throw Error objects.Do not throw plain strings.throw new Error("Invalid input");
25Use async await for readable async code.Do not create deeply nested promise chains.const users = await fetchUsers();
26Handle async errors.Do not ignore rejected promises.try { await fetchUsers(); } catch (error) { showError(); }
27Use Promise.all() for independent tasks.Do not await independent requests one by one.const data = await Promise.all([getUsers(), getOrders()]);
28Check response.ok with Fetch API.Do not assume fetch() throws for HTTP errors.if (!response.ok) { throw new Error("Request failed"); }
29Use JSON.stringify() for browser storage objects.Do not store objects directly in Local Storage.localStorage.setItem("user", JSON.stringify(user));
30Use JSON.parse() safely.Do not parse invalid JSON without handling errors.try { JSON.parse(text); } catch (error) { console.log("Invalid JSON"); }
31Use textContent for plain text.Do not use innerHTML for untrusted text.message.textContent = "Saved successfully";
32Sanitize before using innerHTML.Do not inject unsafe user input into HTML.element.textContent = userInput;
33Use classList for CSS classes.Do not overwrite full class strings unnecessarily.modal.classList.add("show");
34Use addEventListener().Do not use inline HTML event attributes.button.addEventListener("click", handleClick);
35Use event delegation for dynamic lists.Do not attach too many duplicate listeners.list.addEventListener("click", function(event) { console.log(event.target); });
36Clean up timers.Do not leave unused intervals running.clearInterval(intervalId);
37Debounce frequent events.Do not run heavy logic on every keystroke.clearTimeout(timer); timer = setTimeout(search, 300);
38Use requestAnimationFrame() for animations.Do not use timers for smooth animation loops.requestAnimationFrame(animate);
39Validate user input.Do not trust raw form values.if (email === "") { showError("Email is required"); }
40Validate on the server too.Do not rely only on frontend validation.// Server must validate submitted data
41Keep secrets on the server.Do not expose private API keys in frontend code.// Use backend endpoint for secret API calls
42Avoid sensitive data in browser storage.Do not store passwords or private data in Local Storage.localStorage.removeItem("token");
43Write helpful error messages.Do not show vague errors like "Something broke".throw new Error("User ID is required");
44Keep conditions readable.Do not write overly complex boolean logic.if (user.active && user.emailVerified) { allowAccess(); }
45Use early returns.Do not create unnecessary nested blocks.if (!isValid) { return; }
46Comment the reason behind complex code.Do not comment obvious code.// Keep retry low to avoid API rate limits
47Use linting tools.Do not depend only on manual code review.// ESLint catches common JavaScript issues
48Use consistent formatting.Do not mix formatting styles across files.// Prettier keeps formatting consistent
49Write tests for important logic.Do not rely only on manual testing.expect(add(2, 3)).toBe(5);
50Keep code simple and predictable.Do not over-engineer simple problems.const total = price + tax;

Common JavaScript Don'ts to Avoid

  • Do not use var in modern JavaScript unless maintaining legacy code.
  • Do not use == when === is safer and clearer.
  • Do not write large functions that mix many responsibilities.
  • Do not ignore errors in async code, promises, or Fetch API calls.
  • Do not use innerHTML with untrusted user input.
  • Do not store sensitive information in browser storage.
  • Do not rely only on frontend validation for security.
  • Do not leave timers, intervals, or event listeners running unnecessarily.

Key Takeaways

  • JavaScript do's and don'ts help improve code quality and reduce bugs.
  • Use const, let, strict equality, descriptive names, and small functions.
  • Avoid unsafe DOM updates, ignored errors, global variables, and sensitive browser storage.
  • Use modules, async/await, error handling, and validation correctly.
  • Write code that is readable, predictable, secure, testable, and easy to maintain.

Pro Tip

The best JavaScript developers do not only write code that works. They write code that is easy to read, safe to run, simple to debug, and easy for other developers to maintain.