Explain why throwing a custom `RangeError` is a better approach than using `assert` for runtime input validation in the given function.

Node.js interview question for Advanced practice.

Answer

The primary issue is using assert for runtime input validation. Assertions are designed to catch programmer errors or violations of internal invariants, not expected runtime errors like invalid user input. When calculateArea(-5, 10) is called, the assertion fails and throws an AssertionError, which crashes the Node.js application if uncaught. This is unacceptable for a production service. A better approach is to treat invalid input as a predictable runtime error and handle it gracefully by throwing a more appropriate error type. javascript // Improved Version function calculateArea(length, width) { if (typeof length !== 'number' || typeof width !== 'number') { throw new TypeError('Length and width must be numbers.'); } if (length <= 0 || width <= 0) { throw new RangeError('Length and width must be positive numbers.'); } return length width; } // Calling code can now handle this specific error try { console.log(calculateArea(-5, 10)); } catch (error) { if (error instanceof RangeError) { console.error('Invalid input:', error.message); // Gracefully handle the error, e.g., return an error response to a user. } else { // Handle other unexpected errors throw error; } } Throwing a RangeError is better because: 1. It Doesn't Crash the App: The calling code can use a try...catch block to handle the error without terminating the process. 2. Semantic Clarity: RangeError clearly communicates that a value was not in the expected set or range, which is more descriptive than a generic AssertionError.

Explanation

Standard JavaScript Error types like TypeError and RangeError provide more semantic meaning for runtime errors than a generic AssertionError.

Related Questions