Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a string of whitespace truthy or falsy in JavaScript?

Tags:

javascript

This expression ' ' == true returns false, which means ' ' is falsy,

However if(' ') { console.log(' true ') } else { console.log(' false ') } , gets the result true.

Now I am confused, whether the string of whitespace is truthy or falsy?

like image 899
Johnny Chen Avatar asked Nov 14 '15 05:11

Johnny Chen


1 Answers

The string ' ' is a "truthy" value.

Here is a list of the "falsy" values:

false
null
undefined
0
NaN
''

You have to understand that "truthy" is not the same thing as true. A value can be "truthy" without being true. For example, if we did 5 == true, we would get false, even though 5 is a "truthy" value.

In general, pretty much every value is "truthy" (excluding the ones mentioned above). But, the easiest way to check if something is "truthy"/"falsy" is by doing something like this:

var value = valueToTest;

if (value) {
  console.log('Truthy!');
} else {
  console.log('Falsy!');
}
like image 65
Saad Avatar answered Sep 20 '22 20:09

Saad