JS आम गलतियां
In this page:
Assignment बनाम Comparison
= एक value assign करता है जबकि == या === उसकी तुलना करता है; किसी condition के अंदर गलती से if (x = 5) लिख देना चुपचाप x को 5 assign कर देता है और हमेशा truthy evaluate होता है, एक classic पकड़ में मुश्किल आने वाला bug।
उदाहरण: Assignment vs Comparison
let x = 0;
if (x = 5) { // mistake: assignment instead of comparison
console.log("Always runs, x is now", x);
}
Variable Scope की गलतियां
किसी loop या block के अंदर var से एक variable declare करना उसे let की तरह scope नहीं करता, जिससे किसी loop में हर closure अपनी value के बजाय एक ही आखिरी value capture कर सकता है।
उदाहरण: Variable Scope Mistakes
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(() => console.log(i));
}
funcs[0](); // 3, not 0 - var is not block-scoped
Array और Object की गलतियां
किसी array या object को बदल देना जिसे आपने बदलने का इरादा नहीं किया था — उदाहरण के लिए, .sort() (जो in place mutate करता है) कॉल करना जब आपका इरादा original order रखने का था — subtle bugs का एक आम कारण है।
उदाहरण: Array and Object Mistakes
const original = [3, 1, 2];
const sorted = original.sort(); // mutates in place!
console.log(original); // [1, 2, 3] - original changed too
Async और Function की गलतियां
किसी Promise को await करना भूल जाना, या .then() chains को async/await के साथ असंगत तरीके से मिला देना, code को गलत क्रम में चला सकता है या किसी ऐसी error को चुपचाप निगल सकता है जिसे catch block कभी नहीं देखता।
उदाहरण: Async and Function Mistakes
async function getData() {
const result = fetchData(); // forgot await
console.log(result); // logs a Promise, not the resolved value
}
function fetchData() { return Promise.resolve(42); }
getData();
Type और Conversion की गलतियां
=== के बजाय == से values compare करना अनपेक्षित type coercion trigger कर सकता है (जैसे '' == 0 का true होना), जबकि यह मान लेना कि typeof null object है कुछ type-checking logic को गलत दिशा में ले जाता है।
उदाहरण: Type and Conversion Mistakes
console.log('' == 0); // true - unexpected coercion with ==
console.log(typeof null); // "object" - a long-standing quirk
- किसी
ifके अंदर=इस्तेमाल करना, जैसेif (x = 5), जो compare करने के बजाय assign कर देता है। - किसी promise को
awaitकरना भूल जाना, इसलिए code एक pending Promise object के साथ काम करता है। - किसी array पर loop करते हुए उसे modify करना, जो items skip कर देता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: