Require Parameters for JavaScript Functions

By  on  

JavaScript is notorious for being "loose", something that some developers love but other developers loathe.  I hear most of those complaints from server side developers, who want string typing and syntax.  While I like strict coding standards, I also like that JavaScript lets me quickly prototype without having to cross the I's and dot the T's.  Until recently you couldn't define default parameter values for functions in JavaScript, but now you can!

When I posted last week about Six Tiny but Awesome ES6 Features, an awesome reader (cmwd) pointed out that you can not only set default function parameter values but you can throw errors when a given parameter isn't provided to a function:

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

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

// This will throw an error because no name is provided
hello();

// This will also throw an error
hello(undefined);

// These are good!
hello(null);
hello('David');

I love this tip -- it shows how with each addition to JavaScript we can stretch the language to do interesting things.  How practical it is to throw errors in production is up to you but this is an awesome ability during development.  Happy coding!

Recent Features

  • By
    Creating Scrolling Parallax Effects with CSS

    Introduction For quite a long time now websites with the so called "parallax" effect have been really popular. In case you have not heard of this effect, it basically includes different layers of images that are moving in different directions or with different speed. This leads to a...

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    FileReader API

    As broadband speed continues to get faster, the web continues to be more media-centric.  Sometimes that can be good (Netflix, other streaming services), sometimes that can be bad (wanting to read a news article but it has an accompanying useless video with it).  And every social service does...

  • By
    Create a Simple News Scroller Using MooTools, Part I:  The Basics

    News scroller have been around forever on the internet. Why? Because they're usually classy and effective. Over the next few weeks, we'll be taking a simple scroller and making it into a flexible, portable class. We have to crawl before we...

Discussion

  1. decksterr

    Would it still show an exception for say hello(undefined) ? or hello(null) ?

    Just curious, not having set up any ES6 environment yet …

  2. Yes for undefined, no for null (“Hello null”)

  3. Augusto Borges de Moura

    With Method Parameter Decorators proposal, you can even do function (@Required arg) {...}

  4. One trick to do with required params is using TypeError instead of “plain” Error. If you try to call one of the builtin functions without the right amount of params, you’ll get a TypeError, so makes sense to have custom code do that too :)

  5. Adam van den Hoven

    its a little verbose, but you could pass the parameter name into isRequired to get better error messages.

  6. Interesting! And apparently arguments is already available to the default function parameter: https://jsfiddle.net/2447ksz7/

  7. Valtteri

    To get rid of the parenthesis:

    Object.defineProperty(self, 'required', {
    	get () { throw new TypeError('param is required') }
    })
    • @Valtteri: How would you use that? Can you share a more complete example?

  8. This is a great tip! Thanks for sharing. Modified it a bit to make the error more helpful.

    const isRequired = (name, position) => {throw new Error(Paramater "${name}" in position ${position} is required.);};

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!