Reputation: 579
I have this code for my check method:
static emptyOrWhiteSpaceString(obj: string, paramName: string) {
if (obj === null || obj === '' || obj === ' ') {
throw new ServiceException(`${paramName} name is empty.`);
}
}
and I got this suggestion from a reviewer in my pull request:
if (!obj || !obj.trim())
I understand what he wants, but I don't understand the way he is saying it. Please help, how to fix this code according to this answer?
Upvotes: 0
Views: 78
Reputation: 2078
(obj === null || obj === '' || obj === ' ')
does not check for the instances of undefined or when a string has more than one space. your reviewer has fixed both of those issues with his comment.
JS considers most things an object, so the !obj
will test for if the item is actually an object (i.e. not null or undefined or empty)
the obj.trim()
will trim all the whitespace around the string, and if it is empty will return false. this is because an empty string in JS can be converted to a boolean false, ! in this will convert it to true.
Upvotes: 0
Reputation: 1732
static emptyOrWhiteSpaceString(obj: string, paramName: string) {
// change if condition checkes like this
if (!obj || !obj.trim()) {
throw new ServiceException(`${paramName} name is empty.`);
}
}
Upvotes: 1