In javascript, we often see 0 and 1 representing boolean TRUE and FALSE.
When using javascript in conjunction with HTML, values that originate within an HTML element (e.g. a form or ELEMENT attribute) may have a "type" conversion (e.g. "1" or "true" and could be handed through to javascript as a string.
In addition, we may also have different values for TRUE in string form as lower/upper/camel case (TRUE / true / True).
So determining true TRUE can be tricky. I'm wondering if the following function covers all bases, or if i've missed something?
function isFalse (val){
// Just use isTrue so we don't have to test against "" and null
return ! isTrue(val);
// This is the actual code needed to test against FALSE, notice the extra "" and NULL checks
/*
if(typeof val == "string"){
return !(val === "0" || val === "" || val.toLowerCase() === "false");
} else if (typeof val == "object" && val !== null) {
return Object.keys(val).length;
}
return !!val;
*/
}
function isTrue(val){
if(typeof val == "string"){
return (val === "1" || val.toLowerCase() === "true");
} else if (typeof val == "object" && val !== null) {
return Object.keys(val).length;
}
return !!val;
}
// An empty var for testing
var emptyvar;
// A list of test values
// [value is t/f, value]
var list = [
[1, 1]
, [1, "1"]
, [1, true]
, [1, "true"]
, [1, "TRUE"]
, [1, "True"]
, [0, 0]
, [0, "0"]
, [0, false]
, [0, "false"]
, [0, "FALSE"]
, [0, "False"]
, [0, NaN]
, [0, undefined]
, [0, emptyvar]
, [0, null]
, [0, ""]
, [0, {}]
, [0, []]
];
console.log("-------------- is true ---------------------");
for(var i=0; i<list.length; i++){
var item = list[i][1];
var tf = isTrue(item);
console.log( "pass : " + (list[i][0] == tf ? 1 : 0) + " - isTrue : " + tf + " : " + (typeof item) + " : " + item );
}
console.log("-------------- is false ---------------------");
for(var i=0; i<list.length; i++){
var item = list[i][1];
var tf = isFalse(item);
console.log( " pass : " + (list[i][0] == tf ? 0 : 1) + " - isFalse : " + tf + " : " + (typeof item) + " : " + item );
}
The code above passes the tests correctly, but I'm wondering if I've missed something obvious?