I found a another way to test if the value is null:
if(variable >= 0 && typeof variable === "object")
null
acts as a number
and object
at the same time. Comparing null >= 0
or null <= 0
results in true
. Comparing null === 0
or null > 0
or null < 0
will result in false. But as null
is also an object we can detect it as a null.
I made a more complex function natureof witch will do better than typeof and can be told what types to include or keep grouped
/* function natureof(variable, [included types])_x000D_
included types are _x000D_
null - null will result in "undefined" or if included, will result in "null"_x000D_
NaN - NaN will result in "undefined" or if included, will result in "NaN"_x000D_
-infinity - will separate negative -Inifity from "Infinity"_x000D_
number - will split number into "int" or "double"_x000D_
array - will separate "array" from "object"_x000D_
empty - empty "string" will result in "empty" or_x000D_
empty=undefined - empty "string" will result in "undefined"_x000D_
*/_x000D_
function natureof(v, ...types){_x000D_
/*null*/ if(v === null) return types.includes('null') ? "null" : "undefined";_x000D_
/*NaN*/ if(typeof v == "number") return (isNaN(v)) ? types.includes('NaN') ? "NaN" : "undefined" : _x000D_
/*-infinity*/ (v+1 === v) ? (types.includes('-infinity') && v === Number.NEGATIVE_INFINITY) ? "-infinity" : "infinity" : _x000D_
/*number*/ (types.includes('number')) ? (Number.isInteger(v)) ? "int" : "double" : "number";_x000D_
/*array*/ if(typeof v == "object") return (types.includes('array') && Array.isArray(v)) ? "array" : "object";_x000D_
/*empty*/ if(typeof v == "string") return (v == "") ? types.includes('empty') ? "empty" : _x000D_
/*empty=undefined*/ types.includes('empty=undefined') ? "undefined" : "string" : "string";_x000D_
else return typeof v_x000D_
}_x000D_
_x000D_
// DEMO_x000D_
let types = [null, "", "string", undefined, NaN, Infinity, -Infinity, false, "false", true, "true", 0, 1, -1, 0.1, "test", {var:1}, [1,2], {0: 1, 1: 2, length: 2}]_x000D_
_x000D_
for(i in types){_x000D_
console.log("natureof ", types[i], " = ", natureof(types[i], "null", "NaN", "-infinity", "number", "array", "empty=undefined")) _x000D_
}
_x000D_