1

I have a condition checking for empty strings and it is not evaluating an empty string as expected.

I read string one char at a time:

isNumber(s: string) {
  console.log('char', s);
  if (s !== '' && !isNaN(Number(s))) {
    console.log('is a number');
    console.log('-------------');
    return true;
  }
  console.log('NOT a number');
  console.log('-------------');
}

The string is read from a csv file:

a,b,
c,d,e

The 3rd column 1st row is empty but if evaluates to true even though I have s !== '', I have confirmed the char is empty with console. Why is the empty string condition not working?

Update: Could this cause a non empty string? I initialise the variable with quotes then append to it.

cellExtraction = '';
cellExtraction += s; // <- where s should be an empty string read from file
8
  • What exactly does the console.log() show? Commented May 29, 2019 at 11:45
  • 1
    Are you sure it's an empty string or does it have whitespaces " "? Commented May 29, 2019 at 11:46
  • Your expression works properly if s is really the empty string. Therefore one can only conclude that it is not. Note that Number(s) when s is a string containing zero or more space characters returns 0, which is a number. Commented May 29, 2019 at 11:46
  • it is an empty string without any whitespaces Commented May 29, 2019 at 11:49
  • 1
    Actually, 13 is \r - carriage return. Line break is \n which has a char code of 10. You can use s.trim() to remove it and other white space characters. Commented May 29, 2019 at 13:03

1 Answer 1

4

The expression Number("") returns 0, which is a number. Since the s !== '' test is obviously returning true, it must be the case that s contains one or more space characters. Those also are turned into 0 by the Number() function; that is, Number(" ") is also 0.

Sign up to request clarification or add additional context in comments.

5 Comments

looking at console it appears to be an empty string, and in the file its empty, it shouldn't have any space. I'm not concerned about the Number(), can't figure out why there is space and if there isn't how its passing the condition
It's a return key, s.charCodeAt(0) = 13, it looks like an empty string in the console so I guess I could add a condition for: s.charCodeAt(0) != 13
@mattiscodings you could do that, or just do s = s.trim(); before testing to remove leading and trailing white space.
that works even though char code 13 is a line break so I guess it removes line breaks to
@mattiscodings the "white space" category includes more than just spaces; tabs, newlines, probably some "weird" Unicode space-like things, etc

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.