Reputation: 6557
I had a bug that turned out to be because I forgot to check for null values. I added the check, but would like if it could be written more concise.
<ListItem onClick={!pattern.capped && !pattern.hasInlineRef ? search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null) : undefined}>
Can this check for empty or null be shortened?
search(pattern.dbValue, pattern.dbValue === "" || pattern.dbValue === null)
It's written in Typescript, but I guess the curly braces make it JavaScript.
Upvotes: 1
Views: 152
Reputation: 1
You can create an helper function in a separate folder and pull out this function into the files where you need to check for null, undefined, empty string or an empty object.You can write something like this:
export default value =>
value === undefined ||
value === null ||
(typeof value === 'object' && Object.keys(value).length === 0) ||
(typeof value === 'string' && value.trim().length === 0);
Hope this helps
Upvotes: 0
Reputation: 2280
First, you can create an util function to check null, empty or undefined:
export function isNullOrEmpty(value) {
return (value === null || value === undefined || value === "") ? true : false
}
Or, you can fast test with falsy and truthy:
search(pattern.dbValue, !pattern.dbValue)
List of falsy values in JavaScript: MDN Falsy
Upvotes: 2