I have used typeof foo !== 'undefined'
to test optional parameters in javascript functions, but if I want this value to be true
or false
every time, what is the simplest or quickest or most thorough way? It seems like it could be simpler than this:
function logBool(x) {
x = typeof x !== 'undefined' && x ? true : false;
console.log(x);
}
var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true
You could skip the ternary, and evaluate the "not not x", e.g. !!x
.
If x is undefined, !x
is true, so !!x
becomes false again. If x is true, !x
is false so !!x
is true.
function logBool(x) {
x = !!x;
console.log(x);
}
var a, b = false, c = true;
logBool(a); // false
logBool(b); // false
logBool(c); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With