Skip to main content
Home / Code Snippets / JavaScript / Required Parameters for Functions in JavaScript

Ooo this is clever! I’m snagging this from David’s blog.

const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors

// These will not

The idea here is that it uses default parameters, like how the b parameter here has a default if you don’t send it anything:

function multiply(a, b = 1) {
  return a * b;

So above, if you don’t provide a name, it’ll use the default instead, which is that function that throws an error.