1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Properly validating required properties in JS

Discussion in 'Programming/Internet' started by OwenP, Oct 8, 2018.

  1. OwenP

    OwenP Guest

    I'm trying to validate required fields in JS, and I'm relatively new to the language. The most obvious initial way to do so would be:

    function require(input) {
    if (!input) {
    throw new Error("A required property is missing.");
    }
    }


    But as I worked and learned more, I realized there are a lot of "falsy" things that would be false positives in this test. For example, a false property, or something set to 0, isn't intended to throw here.

    So I refactored to:

    function require(input) {
    if (input === undefined || input == null) {
    throw new Error("A required property is missing.");
    }
    }


    Is this the most acceptable way, or is there something more concise I am missing?

    Login To add answer/comment
     

Share This Page