agyanadda@gmail.com

JS Best Practices

Modern JS and Best Practices 1 min read Updated Dec 1, 2026 Topic 38 of 38

Good habits make code easier to read, fix and grow.

Writing code

  • Use const by default, let when needed, never var
  • Always use === and !==
  • Give clear names: totalPrice, isLoggedIn, getUser()
  • Keep functions small — one job per function
  • Avoid global variables; use modules or functions
  • Return early instead of deep nesting

Safety

  • Use textContent for user input, not innerHTML
  • Validate on the server too
  • Never put passwords or secret keys in JavaScript — anyone can read it

Performance

  • Load scripts with defer
  • Select elements once and reuse them
  • Use event delegation for long lists
  • Use debounce for search inputs

Tools

  • Read console errors first
  • Format code with Prettier, check it with ESLint

Example

Example — Clean code: before and after HTML
<pre id="out"></pre>

<script>
  // Before: unclear names, ==, nested ifs
  // function c(a) { if (a) { if (a.m == '33') { return 'p'; } } }

  // After: clear names, early return, strict equality
  const PASS_MARK = 33;

  function getResult(student) {
    if (!student) return 'No data';
    return student.marks >= PASS_MARK ? 'Pass' : 'Fail';
  }

  const students = [
    { name: 'Asha', marks: 82 },
    { name: 'Aman', marks: 21 }
  ];

  document.getElementById('out').textContent = students
    .map(s => `${s.name}: ${getResult(s)}`)
    .join('\n');
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which is the best variable name?

Exercise 2 True / False

It is safe to store secret API keys in front-end JavaScript.

Exercise 3 Fill in the Blank

Always compare with ___ instead of ==.

Frequently Asked Questions

Build small projects (to-do list, quiz, weather app with fetch), then learn a framework like React or Vue, or Node.js for the server side.