Skip to content
jshacks.dev
Functions

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.

1 min read
Summarize in AI

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.

JavaScript
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}`);
  }
}
Text
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.5

TypeError 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.

Taggednode 24
Share

More snippets

Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.