Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

    not-definedpublic

    not-defined

    checks if foo is not defined, i.e. undefined, null, an empty string, array or object

    Installation | Usage | Annotated source | License

    NPM version Dependency Status KLP

    Installation

    npm install not-defined

    Usage

    This snippet of code

    const notDefined = require('not-defined')
     
    if (notDefined(foo)) {
      // do something, usually throw a TypeError
    }

    is equivalent to the following pseudocode

    if (foo is not defined, i.e. is not null, undefined, an empty string, array, object) {
      // do something, usually throw a TypeError
    }
    

    You can also use a shorter but still semantic form like

    const no = require('not-defined')
     
    if (no(foo)) {
      // do something, usually throw a TypeError
    }

    Follows a list of tested examples

    no() // true
    no(undefined) // true
    no(null) // true
    no('') // true
    no([]) // true
    no({}) // true
     
    no(0) // false
    no(true) // false
    no(false) // false
    no('string') // false
    no(['foo']) // false
    no({ foo: true }) // false
    no(42) // false
    no(Infinity) // false
    no(function () { return 1 }) // false

    Pros

    • Type less.
    • Better readability (even your boss will understand your code ^:).
    • Can save bytes in your builds.
    • Easier to autocomplete in editors (for instance easier than typeof foo === 'undefined').

    Annotated source

    This is my first npm package written using KISS Literate Programming. It is plain ES5 function that is 125 characters long.

    module.exports=function(x){return x==null||(x.length<1&&typeof x!='function')||(typeof x=='object'&&Object.keys(x).length<1)}
    

    Snippet length<1 is used instead of equivalent length==0 to save two characters, considering it is used twice.

    License

    MIT

    install

    npm i not-defined

    Downloadslast 7 days

    88

    version

    2.0.2

    license

    MIT

    homepage

    g14n.info

    repository

    github.com

    last publish

    collaborators

    • avatar