✅ Practice + Quiz  ·  Lesson 46

JavaScript Best Practices

JavaScript Best Practices

Variables and Equality — the two golden rules

// ✓ const by default, let when it must change, NEVER var
const siteName = "CodeKaFunda";
let count = 0;
var oldStyle = "avoid";                // ✗

// ✓ Always strict equality
if (age === 18) { }                    // ✓
if (age == 18) { }                     // ✗ type coercion surprises

// ✓ Declare in the smallest scope that works
function calc() {
    const total = 100;                 // local, not global
}
If you follow only two rules from this whole chapter, make them these. First: const by default, let when reassignment is genuinely needed, and never var — you now know why (var ignores block scope and hoists as undefined). Second: always use === and !==, never the loose ==, because type coercion produces results like 0 == false being true. These two habits alone eliminate a large share of real-world JavaScript bugs.

Meaningful Names

// ✗ Meaningless
let d = 5;
let arr = [];
function proc(x) { }

// ✓ Self-documenting
let daysRemaining = 5;
let studentNames = [];
function calculateTotalPrice(items) { }

// Booleans read like questions:
let isLoggedIn = true;
let hasPermission = false;

// Functions start with a verb:
function getUserById(id) { }
function validateEmail(email) { }
Good names make comments unnecessary. Use full words, in camelCase, describing the VALUE not its type. Boolean variables should start with is, has, or can, so conditions read like English: if (isLoggedIn). Function names should start with a verb saying what they DO: calculateTotal, renderList, validateForm. The only acceptable single letters are i in a loop and e for an event. Code is read far more often than it's written — write for the reader.

Small, Focused Functions

// ✗ One function doing four things
function handleForm() {
    // reads inputs, validates, formats, sends, updates DOM...  60 lines
}

// ✓ Each function does ONE thing
function getFormData() { }
function validateData(data) { }
function saveData(data) { }
function showSuccess() { }

function handleForm() {                 // reads like a summary
    const data = getFormData();
    if (!validateData(data)) return;    // guard clause
    saveData(data);
    showSuccess();
}
A function should do ONE thing, and its name should say what that thing is. When a function grows past roughly 20 lines, or you find yourself writing comments like "// now validate", it wants splitting. Small functions are easier to name, test, reuse, and debug — and the top-level function that calls them becomes a readable summary of the whole process. Pair this with guard clauses (early returns for invalid cases) to keep the main logic un-nested and clear.

Defensive DOM Code

// ✗ Crashes if the element isn't found
document.querySelector("#btn").addEventListener("click", handler);

// ✓ Check first
const btn = document.querySelector("#btn");
if (btn) {
    btn.addEventListener("click", handler);
}

// ✓ Cache selections instead of re-querying in a loop
const list = document.querySelector("#list");     // once, outside
items.forEach(item => list.appendChild(makeItem(item)));

// ✓ Safe by default: textContent for anything a user typed
el.textContent = userInput;        // not innerHTML
Three habits prevent most DOM bugs. Check for null before using a selected element — querySelector returns null when nothing matches, and null.addEventListener is the classic TypeError. Cache your selections: query once and store the result rather than calling querySelector inside a loop. And default to textContent over innerHTML for any user-supplied content, closing off XSS. Also remember: scripts must run after the HTML exists (defer, or place before </body>).

Common Mistakes to Avoid

  • Forgetting Number() on input values.value is always a string, so "3" + 5 gives "35".
  • Forgetting e.preventDefault() in a form submit handler — the page reloads and your code never runs.
  • Calling instead of passing a callback: addEventListener("click", fn()) — drop the parentheses.
  • Using = instead of === in an if — it assigns and is usually truthy.
  • Assuming async code runs in orderfetch results arrive later; use await.
  • Polluting the global scope — declare variables inside functions where possible.
  • Leaving console.log in production — clean them out before shipping.
Nearly every item here traces back to a specific lesson in this course. If you internalise the four core habits — const/let, ===, meaningful names, small functions — plus defensive DOM checks and Number() conversion on inputs, your JavaScript will already be cleaner than a great deal of code running on the web today.

Exam Corner

Q: What is the recommended variable declaration order? const by default, let when reassignment is needed, never var.

Q: Why always use === ? == performs type coercion, producing surprising results like 0 == false.

Q: How should boolean variables be named? Starting with is, has, or can — e.g. isLoggedIn.

Q: Why check for null after querySelector? It returns null when nothing matches, and using null throws a TypeError.

Q: How large should a function be? Small — it should do one thing, which its name describes.

Variables और Equality — दो सुनहरे नियम

// ✓ const default, let jab badalna ho, KABHI var nahi
const siteName = "CodeKaFunda";
let count = 0;
var oldStyle = "avoid";                // ✗

// ✓ Hamesha strict equality
if (age === 18) { }                    // ✓
if (age == 18) { }                     // ✗ type coercion ke aashcharya

// ✓ Sabse chhote scope me declare karo
function calc() {
    const total = 100;                 // local, global nahi
}
अगर आप पूरे chapter से सिर्फ दो नियम follow करें, तो ये हों. पहला: default में const, reassignment सच में चाहिए तो let, और कभी var नहीं — अब आप कारण जानते हैं (var block scope ignore करता है और undefined के रूप में hoist होता है). दूसरा: हमेशा === और !== use कीजिए, कभी loose == नहीं, क्योंकि type coercion 0 == false के true होने जैसे नतीजे देता है. ये दो आदतें अकेले असली दुनिया के JavaScript bugs का बड़ा हिस्सा मिटा देती हैं.

सार्थक नाम

// ✗ Bematlab
let d = 5;
let arr = [];
function proc(x) { }

// ✓ Khud-documenting
let daysRemaining = 5;
let studentNames = [];
function calculateTotalPrice(items) { }

// Booleans sawaal jaisa padhte hain:
let isLoggedIn = true;
let hasPermission = false;

// Functions verb se shuru:
function getUserById(id) { }
function validateEmail(email) { }
अच्छे नाम comments को अनावश्यक बना देते हैं. पूरे शब्द use कीजिए, camelCase में, VALUE का वर्णन करते न कि उसके type का. Boolean variables is, has, या can से शुरू होने चाहिए, ताकि conditions अंग्रेज़ी जैसी पढ़ें: if (isLoggedIn). Function नाम verb से शुरू होने चाहिए जो बताए वे KYA करते हैं: calculateTotal, renderList, validateForm. एकमात्र स्वीकार्य single letters loop में i और event के लिए e हैं. Code लिखे जाने से कहीं ज़्यादा पढ़ा जाता है — पढ़ने वाले के लिए लिखिए.

छोटे, केंद्रित Functions

// ✗ Ek function chaar kaam karta
function handleForm() {
    // inputs padhta, validate, format, bhejta, DOM update...  60 lines
}

// ✓ Har function EK kaam karta
function getFormData() { }
function validateData(data) { }
function saveData(data) { }
function showSuccess() { }

function handleForm() {                 // saaransh jaisa padhta hai
    const data = getFormData();
    if (!validateData(data)) return;    // guard clause
    saveData(data);
    showSuccess();
}
Function को EK काम करना चाहिए, और उसका नाम बताए वह काम क्या है. जब function लगभग 20 lines से बड़ा हो, या आप "// अब validate करो" जैसी comments लिखते पाएं, वह बंटना चाहता है. छोटे functions नाम देने, test करने, reuse करने, और debug करने में आसान हैं — और उन्हें call करने वाला top-level function पूरी प्रक्रिया का पढ़ने योग्य सारांश बन जाता है. इसे guard clauses (अमान्य मामलों के लिए early returns) से जोड़िए ताकि मुख्य logic बिना nesting और साफ रहे.

सतर्क DOM Code

// ✗ Element na mile to crash
document.querySelector("#btn").addEventListener("click", handler);

// ✓ Pehle jaancho
const btn = document.querySelector("#btn");
if (btn) {
    btn.addEventListener("click", handler);
}

// ✓ Loop me dobara query karne ke bajaye selections cache karo
const list = document.querySelector("#list");     // ek baar, bahar
items.forEach(item => list.appendChild(makeItem(item)));

// ✓ Default me surakshit: user ke type kiye kuch bhi ke liye textContent
el.textContent = userInput;        // innerHTML nahi
तीन आदतें ज़्यादातर DOM bugs रोकती हैं. Selected element use करने से पहले null जांचिए — कुछ न मिलने पर querySelector null लौटाता है, और null.addEventListener classic TypeError है. अपनी selections cache कीजिए: loop के अंदर querySelector call करने के बजाय एक बार query करके नतीजा रखिए. और user के दिए content के लिए innerHTML पर textContent default रखिए, XSS बंद करते. यह भी याद रखिए: scripts HTML बनने के बाद चलनी चाहिए (defer, या </body> से पहले).

टालने योग्य आम गलतियां

  • Input values पर Number() भूलना.value हमेशा string है, तो "3" + 5 "35" देता है.
  • Form submit handler में e.preventDefault() भूलना — page reload होता है और आपका code कभी नहीं चलता.
  • Callback pass करने के बजाय call करना: addEventListener("click", fn()) — parentheses हटाइए.
  • if में === के बजाय = — यह assign करता है और आमतौर पर truthy होता है.
  • Async code order में चलता मान लेनाfetch नतीजे बाद में आते हैं; await use कीजिए.
  • Global scope गंदा करना — जहां हो सके variables functions के अंदर declare कीजिए.
  • Production में console.log छोड़ना — भेजने से पहले साफ कीजिए.
यहां की लगभग हर बात इस course के किसी खास पाठ पर लौटती है. अगर आप चार core आदतें आत्मसात करें — const/let, ===, सार्थक नाम, छोटे functions — साथ ही सतर्क DOM जांच और inputs पर Number() conversion, तो आपकी JavaScript पहले से ही आज web पर चल रहे बहुत सारे code से साफ होगी.

Exam Corner

Q: Variable declaration का recommended order क्या है? Default में const, reassignment चाहिए तो let, कभी var नहीं.

Q: हमेशा === क्यों use करें? == type coercion करता है, 0 == false जैसे आश्चर्यजनक नतीजे देते.

Q: Boolean variables का नाम कैसा हो? is, has, या can से शुरू — जैसे isLoggedIn.

Q: querySelector के बाद null क्यों जांचें? कुछ न मिलने पर यह null लौटाता है, और null use करना TypeError फेंकता है.

Q: Function कितना बड़ा होना चाहिए? छोटा — उसे एक काम करना चाहिए, जिसका उसका नाम वर्णन करे.
← Back to JavaScript Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

इस पेज का code यहाँ तैयार है — बदलिए और तुरंत नतीजा देखिए. कुछ install किए बिना.
👁 Live Preview
सब कुछ आपके browser में ही चलता है — कोई server, कोई signup नहीं. JavaScript का console.log देखने के लिए F12 दबाइए.