! not
a=3;
b=2;
a>b = true
!(a>b) = !(true) = false
I want to write a function without using !
I want to write a function instead of !
How can I do this?
is this right?
Actually, it just occurred to me that it is not. For one, youâd have to use the equality operator, not identity â as in your OP indeed. :-$ Also, youâd have to account for null / undefined and NaN. Thus the function should be
function not(bu) {
return bu == false ||
bu == null ||
isNaN(bu);
}
not(''); // returns true
not(null); // returns true
not(undefined); // returns true
not(0/0); // returns true
Ah yes of course, a string isNaN also⌠didnât think of that. Dealing with NaN is notoriously difficult; yes you cold check if typeof the value in question is a String instead, but then youâd have to check if itâs an Object, a Boolean etc. as well.
I think it would be more elegant to to take advantage of the fact that NaN !== NaN, so the result of every invalid Number operaration will be unequal to itself. Thus you could do this:
function not(bu) {
return bu == false ||
bu == null ||
bu !== bu;
}
not(''); // returns true
not('foo'); // returns false
not(0); // returns true
not(1); // returns false
not(0/0); // returns true
not({}); // returns false
Thatâs more of a brain-teaser than I initially thought anyway. :-)
get rid of the document.write call - that command has been obsolete for over 12 years.
console.log is better for debugging than alert as it doesnât stop the script from continuing to run.
the entire discussion has been about how it is a lot more complicated than that - thatâs why there are three tests in the not function instead of one