7. Conditional Statement and Exceptional Handling in Javascript
Conditional Statement
if-else statement: The
if-else
statement executes a block of code if a specified condition evaluates totrue
, otherwise, it executes another block of code.let num = 10; if (num > 0) { console.log("The number is positive."); } else { console.log("The number is not positive."); }
2. if else-if else statement
let marks = 75;
if (marks >= 90) {
console.log("Grade: A");
} else if (marks >= 75) {
console.log("Grade: B");
} else {
console.log("Grade: C");
}
3. switch statement: The switch
statement evaluates an expression and executes the corresponding case
block based on the matching value.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is coming!");
break;
default:
console.log("Regular day.");
}
Exception Handling
JavaScript provides
try
,catch
,finally
, andthrow
to handle exceptions (errors) in a program.try-catch statement
The
try
block contains the code that may throw an error, and thecatch
block handles the error.try { let x = y; // y is not defined, this will cause an error } catch (error) { console.log("An error occurred:", error.message); }
2. finally statement
The finally
block executes regardless of whether an error occurs or not.
try {
let num = 10;
console.log(num.toUpperCase()); // Will cause an error
} catch (error) {
console.log("Error:", error.message);
} finally {
console.log("Execution completed.");
}
/* Output
Error: num.toUpperCase is not a function
Execution completed.
*/
3. throw statement
The throw
statement allows you to create custom errors.
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older.");
}
return "Access granted!";
}
try {
console.log(checkAge(16));
} catch (error) {
console.log("Error:", error.message);
}
//output
//You must be 18 or older.
Error Objects
JavaScript provides built-in error objects, such as:
Error
: Generic error object.ReferenceError
: Occurs when a non-existent variable is accessed.TypeError
: Occurs when a value is not of the expected type.SyntaxError
: Occurs when there is a syntax mistake in the code.// ReferenceError Example try { console.log(x); // x is not defined } catch (error) { console.log("ReferenceError:", error.message); } // TypeError Example try { let num = 10; num(); // Trying to call a number as a function } catch (error) { console.log("TypeError:", error.message); } // SyntaxError Example (Uncommenting will cause script failure) // try { // eval("console.log('Hello')"); // Invalid JavaScript code // } catch (error) { // console.log("SyntaxError:", error.message); // }
INTERVIEW QUESTIONS
What is the difference between
if-else
andswitch
statements?if-else
is used for evaluating conditions with comparison operators (>
,<
,===
).switch
is used for checking multiple possible values of an expression.
What will be the output of following code ?
let x = 5; if (x = 10) { console.log("x is 10"); } else { console.log("x is not 10"); }
The output will be "x is 10" because
x = 10
is an assignment, not a comparison (===
), so the condition evaluates totrue
.What will happen if there is an error inside the
catch
block?If an error occurs inside the
catch
block, it will not be handled by itself. You would need anothertry-catch
to handle it.What will be the output of following code ?
try { console.log("Start"); throw new Error("Something went wrong!"); console.log("End"); // Will this execute? } catch (err) { console.log("Caught:", err.message); } finally { console.log("Finally executed"); }
Start
Caught: Something went wrong!
Finally executed