JS डिबगिंग
In this page:
console.log(value);
debugger;
console.error(value);
console.table(data);
Debugging क्या है
Debugging यह पद्धतिगत तरीके से ढूंढने की प्रक्रिया है कि code उम्मीद के मुताबिक व्यवहार क्यों नहीं कर रहा, आमतौर पर कारण का अंदाज़ा लगाने के बजाय execution के अलग-अलग points पर values जांचकर।
उदाहरण: What Is Debugging
const value = 5 + "5"; // unexpected result?
console.log(value); // inspect it directly instead of guessing
console Methods
console.log() जल्दी देखने के लिए values print करता है, जबकि console.table(), console.error(), और console.warn() ज़्यादा जटिल debugging sessions में आसानी से scan करने के लिए output को format या categorize करते हैं।
उदाहरण: console Methods
// Call `console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }])`
// Call `console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }])`
console.table([{ id: 1, name: "Sam" }, { id: 2, name: "Amit" }]);
// Print "Something went wrong" to the console as an error
// Print "Something went wrong" to the console as an error
console.error("Something went wrong");
// Print "This is deprecated" to the console as a warning
// Print "This is deprecated" to the console as a warning
console.warn("This is deprecated");
Breakpoints और Debugger
एक breakpoint execution को एक खास line पर रोक देता है ताकि आप सिर्फ print statements पर निर्भर रहने के बजाय browser या Node debugger में variables जांच सकें और code को एक-एक statement करके step through कर सकें।
उदाहरण: Breakpoints and Debugger
function calculate(a, b) {
debugger; // pauses execution here in dev tools
return a + b;
}
calculate(2, 3);
Debugging के दौरान Errors संभालना
error-prone code को debug करते समय, पूरे error object को catch और log करें (सिर्फ उसका message नहीं) ताकि आप वह stack trace रखें जो ठीक-ठीक दिखाता है कि failure कहाँ और कैसे शुरू हुई।
उदाहरण: Handling Errors While Debugging
try {
JSON.parse("bad json");
} catch (error) {
console.log(error); // log the full error object, not just error.message
}
Debugging Best Practices
bug को सबसे छोटे संभव उदाहरण से reproduce करें, कारण के बारे में एक hypothesis बनाएं, और उसे एक targeted check से verify करें — यह randomly code बदलने और फिर से चलाने से तेज़ है।
उदाहरण: Debugging Best Practices
// Reproduce with the smallest example, then verify a hypothesis:
function add(a, b) { return a + b; }
console.log(add(2, "3")); // hypothesis: string coercion is happening
- production code में
console.logयाdebuggerstatements छोड़ देना। - किसी object को log करना और बाद में console के दिखाने पर भरोसा करना, क्योंकि उसे expand करने पर उसकी current values दिखती हैं, log time की values नहीं।
- console error में stack trace को नजरअंदाज करना, जो file और line दिखाता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: