Good habits make code easier to read, fix and grow.
Writing code
- Use
constby default,letwhen needed, nevervar - 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
textContentfor user input, notinnerHTML - 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>