I'm reading through some code with the snippet:
search(query: string) {
of(query).
pipe(
filter(Boolean),
debounceTime(300),
Is filter(Boolean)
essentially the same thing as filter(v=>!!v)
?
Yes, they are the same.
console.log(typeof Boolean); // prints function
console.log(Boolean.prototype.constructor("truthy")); // prints true
console.log(Boolean === Boolean.prototype.constructor); // prints true
The Boolean
global reference points to the constructor function which returns a boolean value from the first argument.
The constructor can be used to create a boolean wrapper object, but it is not the same as the primitive true value.
console.log(new Boolean("truthy")); // prints an object.
console.log(new Boolean("truthy").valueOf() === true); // prints true
console.log((new Boolean("truthy")) === true); // prints false
console.log(Boolean("truthy") === true); // prints true
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean
They achieve the same result in that you don't get undefined values in your subscription.
The difference is that you lose Type Inference when using filter(Boolean)
const query = 'the query';
of(query).
pipe(
filter(Boolean)
).subscribe(val); // val here is of type 'Any'
of(query).
pipe(
filter(Boolean)
).subscribe((val: string)); // we can infer it back to string later
of(query).
pipe(
filter(v=> v!== undefined)
).subscribe(val); // val here is of type 'string'
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