nv-facutil-to-bool
v1.0.0
Published
A stricter boolean conversion function that treats a comprehensive set of "empty" or "falsy-like" values as `false`.
Readme
to-bool
A stricter boolean conversion function that treats a comprehensive set of "empty" or "falsy-like" values as false.
Overview
JavaScript's built-in boolean conversion (!!value or Boolean(value)) only treats a limited set of values as falsy:
false,0,0n,'',null,undefined,NaN
This to-bool function extends that concept to treat many "empty" or "meaningless" values as false, including:
- Empty containers (arrays, objects, Sets, Maps)
- Zero-length binary data structures
- Invalid dates
- Symbols
- Regular expressions
- And more
Installation
npm install to-boolUsage
const toBool = require('nv-facutil-to-bool');
// Basic falsy values
toBool(0); // false
toBool(false); // false
toBool(null); // false
toBool(undefined); // false
toBool(''); // false
toBool(0n); // false
toBool(NaN); // false
// Empty containers
toBool([]); // false
toBool({}); // false
toBool(Object.create(null)); // false
toBool(new Set()); // false
toBool(new Map()); // false
// Wrapper objects with falsy values
toBool(new Number(0)); // false
toBool(new String('')); // false
toBool(new Boolean(false)); // false
// Special objects
toBool(Symbol()); // false - no description
toBool(Symbol('')); // false - empty description
toBool(Symbol.for()); // false - undefined description
toBool(Symbol.for('undefined')); // false - "undefined" key
toBool(Symbol('test')); // true - has description
toBool(Symbol.for('test')); // true - has key
toBool(new Date(NaN)); // false
toBool(/^$/); // false - matches empty string only
toBool(/pattern/); // true - other RegExp
toBool(/(?:)/); // true - other RegExp
// Zero-length binary data
toBool(new Uint8Array(0)); // false
toBool(new ArrayBuffer(0)); // false
toBool(new DataView(new ArrayBuffer(0))); // false
toBool(Buffer.alloc(0)); // false (Node.js)
// Everything else is truthy
toBool(1); // true
toBool('hello'); // true
toBool([1, 2, 3]); // true
toBool({key: 'value'}); // true
toBool(new Date()); // true
toBool(new Uint8Array(10)); // trueTreated as False
The following value types return false:
Primitive Falsy Values
0- zerofalse- boolean falsenull- nullundefined- undefined''- empty string0n- BigInt zeroNaN- Not a Number
Symbols
Symbol()- Symbol without descriptionSymbol('')- Symbol with empty string descriptionSymbol(undefined)- Symbol with undefined as descriptionSymbol.for('undefined')- Global symbol with "undefined" as key
Empty Containers
[]- empty array{}- empty plain objectObject.create(null)- empty null-prototype objectnew Set()- empty Setnew Map()- empty Map
Wrapper Objects with Falsy Values
new Number(0)- Number object wrapping 0new String('')- String object wrapping empty stringnew Boolean(false)- Boolean object wrapping false
Special Objects
new Date(NaN)- Invalid Date/^$/ornew RegExp("^$")- RegExp that only matches empty strings
Binary Data with Zero Length
new Uint8Array(0)- and all other TypedArray variantsnew ArrayBuffer(0)- zero-byte ArrayBuffernew DataView(new ArrayBuffer(0))- DataView of zero-length buffernew SharedArrayBuffer(0)- zero-byte SharedArrayBuffer (if available)Buffer.alloc(0)- zero-byte Node.js Buffer (if available)
Treated as True
Everything else returns true, including:
- Non-zero numbers:
1,-1,3.14,Infinity - Non-empty strings:
'hello','0','false' - Non-empty arrays:
[1],[0],[null] - Non-empty objects:
{a: 1},{length: 0} - Functions:
function() {},() => {} - Non-empty Sets/Maps:
new Set([1]),new Map([['a', 1]]) - Valid dates:
new Date(),new Date(0) - Non-zero binary data:
new Uint8Array(10),Buffer.from('hello') - Wrapper objects with truthy values:
new Number(1),new String('a') - Most RegExp instances:
/test/,/(?:)/,/\d+/(only/^$/is falsy)
Use Cases
Form Validation
function validateForm(formData) {
if (!toBool(formData.name)) {
throw new Error('Name is required');
}
if (!toBool(formData.items)) {
throw new Error('Items array cannot be empty');
}
}Data Processing
function processData(data) {
// Filter out all "empty" values
return data.filter(toBool);
}
const data = [1, 0, 'hello', '', [], [1, 2], {}, {a: 1}, null];
const cleaned = data.filter(toBool);
// [1, 'hello', [1, 2], {a: 1}]Conditional Logic
function shouldProcess(config) {
// Only process if config has meaningful content
if (toBool(config)) {
performAction(config);
}
}API
toBool(value)
Parameters:
value(any): The value to test
Returns:
boolean:falseif the value matches any of the defined "falsy-like" conditions,trueotherwise
Example:
const toBool = require('./to-bool');
console.log(toBool([])); // false - empty array
console.log(toBool([1])); // true - non-empty array
console.log(toBool(new Map())); // false - empty Map
console.log(toBool(/test/)); // false - any RegExpDifferences from Standard Boolean Conversion
| Value | Boolean(value) | toBool(value) |
|-------|-----------------|-----------------|
| [] | true | false |
| {} | true | false |
| new Set() | true | false |
| new Number(0) | true | false |
| Symbol() | true | false |
| Symbol('') | true | false |
| Symbol('test') | true | true |
| /^$/ | true | false |
| /test/ | true | true |
| new Date(NaN) | true | false |
| new Uint8Array(0) | true | false |
