Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active June 5, 2020 06:05
Show Gist options
  • Save dfkaye/1c648bd9a97d9bf21d153128a8ce26d0 to your computer and use it in GitHub Desktop.
Save dfkaye/1c648bd9a97d9bf21d153128a8ce26d0 to your computer and use it in GitHub Desktop.
isValue() checks that a value is not undefined, not null, not NaN, and not an empty string.
// 4 June 2020
// Value check that cuts through tiresome debates.
// Counterpart to isEmpty() which checks for empty containers.
// @see https://gist.github.com/dfkaye/f87272098c4e19e4d55a6a18515aefce
// Stricter version of noValue() from July 2019 which treats empty arrays and empty objects as
// not-containing-values.
// @see https://gist.github.com/dfkaye/e24b35e5cdc66b010cf95766f37ed4ca
/**
* @function isValue() checks that an argument is a value. A value is not undefined, not null, not
* NaN, and not an empty string (and not an empty String instance).
*
* @param {*}
* @returns {boolean}
*/
function isValue(o) {
var undef = o == null;
var nan = o !== o;
var empty = Object(o).valueOf() === '';
return !(undef || nan || empty);
}
/* Test it out */
var shouldReturnFalse = [
null,
void 0,
NaN,
'',
new String()
];
console.assert(shouldReturnFalse.every(item => !isValue(item)));
var shouldReturnTrue = [
' ',
-0,
false,
[/* empty array */],
{/* empty object */}
];
console.assert(shouldReturnTrue.every(item => isValue(item)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment