-5

I have a condition where 0 or more is valid and negative is invalid. When I write code accordingly in JavaScript/TypeScript, to my surprise it's not working the way I expected it to.

The code is as follows.

if (-1) {
  console.log("truthy")
} else {
  console.log("falsy")
}

And this prints the following in console.

truthy

It should have be falsy, right?

Any help, helping me understand this behavior. What am I missing?

Thanks

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
kathikeyan A
  • 1,668
  • 2
  • 16
  • 31

3 Answers3

7

There are six falsy values in JavaScript:

  • false
  • 0
  • NaN
  • undefined
  • ''
  • null

All other values are truthy.

pete
  • 24,141
  • 4
  • 37
  • 51
0

In Javascript, 0 is always evaluated to falsy, and any non-zero number is truthy.

Ruben Krueger
  • 51
  • 2
  • 4
0

In javascript non-zero numbers evaluate to true while zero evaluates to false. Heres a nice webpage that goes deep on the boolean evaluations of many different values in javascript: https://www.sitepoint.com/javascript-truthy-falsy/

Zackary Jones
  • 371
  • 1
  • 9