2

This javascript console log is confusing me. How can x which has the value of -1 be evaluated to true in the if statement where it false the line before it? Thanks

x = -1
-1
x == true
false
if(x){console.log('yes')}
yes
Fred J.
  • 5,080
  • 8
  • 50
  • 95

2 Answers2

1

When you test x in your if statement, you're not checking if x is true, you're checking if x is truthey. The rules for truthiness in javascript are:

empty strings are falsey. all other strings are truthy. 0 and NaN are falsey. all other numbers are truthy. all objects and arrays are truthy. null and undefined are falsey.

Raphael Serota
  • 1,957
  • 9
  • 16
0
if(-1){console.log('yes')}

prints 'yes' in console because -1 and other numbers except 0 are truthey value, despite -1 not equal to true.

Here is a good source for extending knowledge related to javascript truthey and falsey values.

simon
  • 1,375
  • 1
  • 14
  • 23