1

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.

3
  • 2
    "It's written in Typescript, but I guess the curly braces make it JavaScript." all TypeScript compiles to JavaScript. At runtime, you only have JS running. Commented Sep 30, 2019 at 6:46
  • 3
    At least extract the dbValue property first, I think. If its only falsey values are the empty string and null, just call Boolean on it in the second argument Commented Sep 30, 2019 at 6:46
  • you can write some util function for that and use the function to get rid of long code. One more additional thing is undefined check Commented Sep 30, 2019 at 6:48

2 Answers 2

2

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

  1. false
  2. null
  3. undefined
  4. 0
  5. NaN
  6. ''
  7. document.all
Sign up to request clarification or add additional context in comments.

6 Comments

yup, it is a good practice to isolate a function one of few reasons is, easy testing.
Equality checks are already truthy/falsy, just return value === null || value === undefined || value === "";, or because all those values are falsey values, just double-bang it, return !!value;. The only reason I can see for explicit checks is if 0 or NaN needed to be treated differently.
!value would be enough, yes.
Edit went in same time as my comment. :)
@DrewReese but then that would also catch 0 which might be undesirable.
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.