What is Bug
A bug in JavaScript is like a hidden mistake in your code that makes it behave in a way you didn't expect, causing errors or unexpected outcomes.
Example: Imagine you're baking cookies, but you accidentally put salt instead of sugar . Just like that, a bug in JavaScript is when you make a mistake in your code that messes things up, like making your program do something weird or not work properly.
function add(a, b) {
return a + b;
}
console.log(add("1",2)); // prints 12 instead of 3
Error
There are three common types of error are seen during coding
Reference Error
console.log(c + b); //gives reference error: c is not defined
TypeError:
when you try to run different data type method on some other datatype(5).pop; // says 5.pop is not a function
Syntax Erorr:
A piece of code that javascript cannot readvar a = "Hello; //gives syntax error
Error Handling:
try {
console.log(c + b);
}catch(error){
console.log(error);
}
// -------- OR -------- //
try {
throw new ReferenceError();
} catch (err) {
console.log("This was a reference error");
}
console.log("Programe does not stop");
Benefits
Error handling is like having a safety net for your code. It catches mistakes and prevents your program from crashing. It ensures your program can recover from errors and keep running smoothly. Without it, even small mistakes can cause big problems in your code.