0

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())

enter image description here

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?

4
  • @CertainPerformance sorry, I was working in this, I fixed it, and now its looking how it was before the review Commented Nov 20, 2020 at 15:45
  • trim() removes the whitespace from both ends of a string, effectively making obj === ' ' no longer needed. Not sure what the screenshot is, but it looks like it is returning booleans, which would probably be better to return false or true rather than throw an Exception. Commented Nov 20, 2020 at 15:48
  • What is the requirement? Your code and the code of the reviewer do different things. There is no way we can "fix" the code as we don't know what it is supposed to do. Commented Nov 20, 2020 at 15:51
  • @str both codes must return a throw exception if there is no name or similar in the object Commented Nov 20, 2020 at 15:54

2 Answers 2

1
static emptyOrWhiteSpaceString(obj: string, paramName: string) {

    // change if condition checkes like this
    if (!obj || !obj.trim()) {
        throw new ServiceException(`${paramName} name is empty.`);
     }
   }
Sign up to request clarification or add additional context in comments.

1 Comment

ahhhhh this is clear, below the code those are examples... I never would think of that, I am watching the world as code at this point... I thought the examples were more code...
0

(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.

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.