Skip to content

Instantly share code, notes, and snippets.

@DaveyJake
Last active February 20, 2023 19:24
Show Gist options
  • Save DaveyJake/a1a3a42006f73043d43e1ec968b9c476 to your computer and use it in GitHub Desktop.
Save DaveyJake/a1a3a42006f73043d43e1ec968b9c476 to your computer and use it in GitHub Desktop.
PHP-like `empty` Function in Vanilla JS
/**
* Like PHP's {@link https://www.php.net/manual/en/function.empty.php `empty`} function in vanilla JavaScript.
*
* @author Davey Jacobson <daveyjake21 [at] geemail [dot] com>
* @since 1.0.0
* @since 1.0.1 Gist made public.
*
* @param {array|bool|number|object|string} value The value to check.
* @param {bool} [strict=false] Enable strict checking. Accepts true, false.
*
* @return {bool} False if `value` contains anything. True if not. Default false.
*/
function empty( $value, $strict ) {
// Strict checking is disabled by default.
$strict = $strict || false;
/**
* Values and items that are inherently empty.
*
* @since 1.0.0
* @since 1.0.1 Added 'null' and 'undefined'.
* @since 1.0.2 Added `NaN` and 'NaN'.
*
* @type array
*/
var emptyValues = [ 0, '0', false, 'false', '', [], {}, NaN, 'NaN', null, 'null', undefined, 'undefined' ];
// Result of testing `$value`.
var result;
// Checking the `$value`.
if ( ! $strict ) {
// Check if `$value` is found inside the `emptyValues` array.
result = emptyValues.indexOf( $value );
// If the `result` is greater than -1, `$value` is one of the `emptyValues` elements.
return result > -1 ? true : false;
} else {
/**
* Strictly check the value to confirm it's not inherently empty.
*
* @since 1.0.0
*
* @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
*/
result = emptyValues.reduce( function( sum, current ) {
// Check if `current` explicitly matches the `value`.
var i = ( current === $value ? 1 : 0 );
return sum + i;
});
// If `result` is greater than 0, we know it's inherently empty.
return result > 0 ? true : false;
}
// Just in case something goes wrong and we end up here.
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment