1

I'm using the below function to do string validation:

isValidString = value => (value && value.trim() !== '');

I'm expecting a boolean return, but when value = '' return value is an empty string.

Can someone please explain why this is happening?

David Walschots
  • 12,279
  • 5
  • 36
  • 59
Himavanth
  • 400
  • 5
  • 15
  • 1
    Possible duplicate of [Why don't logical operators (&& and ||) always return a boolean result?](https://stackoverflow.com/questions/5417969/why-dont-logical-operators-and-always-return-a-boolean-result) – Ivar Sep 17 '18 at 11:27

3 Answers3

2

Try this.

&& operator don't assign Boolean values but return value of last executed expression. for example in above method if you pass empty string then it return value as empty string equivalent to false. and if you pass non empty string then second part will return value.trim() !== '' which is either true of false.

    isValidString = value => !!(value && value.trim() !== '');
    console.log(isValidString(""))
    console.log(isValidString("a"))
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • `&& operator don't assign Boolean values but return value of last executed expression` - took some time but when understood made my day. Thanks! – Himavanth Sep 17 '18 at 11:36
0

Strings with length 0 are evaluated as false in Boolean expressions in JavaScript, and since you are using the short circuit Boolean AND operator which stops further evaluation when it encounters a false value. Hence your expression returns an empty string as it caused your expression to evaluate to false.

0

You could check if value is undefined using typeof value ! = 'undefined'

isValidString = value => typeof value != 'undefined' && value.trim() !== '';
PicTools
  • 39
  • 3