Branch your code with if/else and switch. Handle runtime errors gracefully with try/catch/finally, throw, and the built-in Error types.
Why: if/else branches on any boolean expression. switch is more readable when comparing one value against many fixed cases.
const score = 72;
if (score >= 90) {
console.log('A');
} else if (score >= 80) {
console.log('B');
} else if (score >= 70) {
console.log('C');
} else {
console.log('F');
}
// switch — falls through unless you break
const day = 'Monday';
switch (day) {
case 'Saturday':
case 'Sunday':
console.log('Weekend'); break;
case 'Monday':
console.log('Start of the week'); break;
default:
console.log('Weekday');
}Why: try/catch intercepts runtime errors so your program can recover gracefully. finally always runs — use it to clean up resources.
// Basic try/catch
try {
const data = JSON.parse('not valid json');
console.log(data);
} catch (err) {
console.log('Caught:', err.message);
}
// throw custom errors
function divide(a, b) {
if (b === 0) throw new RangeError('Cannot divide by zero');
return a / b;
}
try {
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // throws
} catch (err) {
console.log(`${err.name}: ${err.message}`);
} finally {
console.log('always runs');
}
// Error types: Error, TypeError, RangeError, SyntaxError, ReferenceError
try {
null.property;
} catch (e) {
console.log(e instanceof TypeError); // true
}