Write a function that validates its own arguments
Write a function that validates its own arguments in JavaScript, throwing a TypeError with a clear message before the body runs. Node.js 24.
Fail early with a message that names the problem. A check at the top of a function is better than a vague error three calls deeper.
function repeat(text, times) {
if (typeof text !== 'string') {
throw new TypeError(`text must be a string, got ${typeof text}`);
}
if (!Number.isInteger(times) || times < 0) {
throw new RangeError(`times must be a non-negative integer, got ${times}`);
}
return text.repeat(times);
}
console.log(repeat('ab', 3));
for (const args of [[42, 2], ['ab', -1], ['ab', 1.5]]) {
try {
repeat(...args);
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}ababab
TypeError: text must be a string, got number
RangeError: times must be a non-negative integer, got -1
RangeError: times must be a non-negative integer, got 1.5TypeError fits a wrong type and RangeError fits a value outside the allowed range. Putting the received value in the message saves a debugging session.
Check only at boundaries, such as public functions and input from outside. Internal helpers that are called by trusted code do not need it, and TypeScript covers many of these cases at build time but not the data that arrives at runtime.