DEV Community

Rahimuddin
Rahimuddin

Posted on

Minimize the below code

How to handle this with less code?

if (customerIdNumber === '' || customerIdNumber === 'null' || customerIdNumber === null || isNaN(customerIdNumber)) {
alert('success');
}

I'm already using lodash library in the project. So I've tried to use this.
_.isEmpty(customerIdNumber) but this doesn't work for all above.

Top comments (4)

Collapse
 
_garybell profile image
Gary Bell

You could try:

if (isNaN(parseFloat(customerIdNumber)) {
  alert('success');
}
Enter fullscreen mode Exit fullscreen mode

Based off the following:
Webtools console output

Collapse
 
macsikora profile image
Pragmatic Maciej • Edited

Instead of fixing this code you should think why this variable can be in such states. Looking at variable name it should be defined as number | null in TS notation. That is why the only check should be done is simple if(!customerIdnumber).

If any dev is in such situation that such checks need to be done, then I am sure that the origin of this is in different place. Fix the problem and not symptoms.

Collapse
 
codebynao profile image
Naomi

It doesn't seem like he's using TS. Also the check if(!customerIdnumber) wouldn't work since customerIdnumber should also be valid if it is equal to 0.
I agree that something could probably be done elsewhere to avoid this long check. But without context, it seems like @_garybell is a good solution!

Collapse
 
macsikora profile image
Pragmatic Maciej • Edited

I don't think there exists Id which is 0 but your point is correct and the proper check would !== null. That's the whole thing should be done here.

Also I only mentioned TS to describe what type has this variable. You don't need to use explicit types, you still have types.