checks if foo is not defined, i.e. undefined, null, an empty string, array, object or NaN
npm install not-defined> checks if foo is not defined, i.e. undefined, null, an empty string, array, object or NaN
``shell`
npm install not-defined
* Type less.
* Better readability (even your boss will understand your code ^:).
* Can save bytes in your builds (not-defined module occupies only 171B).
* Easier to autocomplete in editors (for instance easier than typeof foo === 'undefined').
Signature is:
`ts`
function notDefined(arg: any): boolean;
This snippet of code
`js
import notDefined from '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 null, undefined, NaN, an empty string, array or object) {
// do something, usually throw a TypeError
}
You can also use a shorter but still semantic form like
`js
import no from 'not-defined'
if (no(foo)) {
// do something, usually throw a TypeError
}
`
A real use case: suppose you have a JSX that gets an array of items from an API.items
If the array of is empty, you want to render a message.
Instead of
` Loading...js
if (isLoading) {
return
}
if (Array.isArray(items) && items.length === 0) {
return
No items found
you can write
`js
if (isLoading) {
return Loading...
}if (no(items)) {
return
No items found
}
`Follows a list of tested examples
`js
no() // true
no(undefined) // true
no(null) // true
no('') // true
no([]) // true
no({}) // true
no(NaN) // trueno(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
no(0n) // false
no(Symbol('foo')) // false
``