If (animating number) is true? Is there something wrong with js?

Is there something wrong with js?

if("hello".indexOf("world")) { // I forgot to add > -1 here
    console.log("hello world");
}

In principle if(-1), true. How is this possible? It took me a whole day to fix this. Is there a list where such things are listed? Or the tools available to capture such things.

+1
source share
4 answers

According to the ECMA 5.1 Standard Specification , the following table is used to determine the likelihood of an expression

+-----------------------------------------------------------------------+
| Argument Type | Result                                                |
|:--------------|------------------------------------------------------:|
| Undefined     | false                                                 |
|---------------|-------------------------------------------------------|
| Null          | false                                                 |
|---------------|-------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion). |
|---------------|-------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;|
|               | otherwise the result is true.                         |
|---------------|-------------------------------------------------------|
| String        | The result is false if the argument is the empty      |
|               | String (its length is zero); otherwise the result is  |
|               | true.                                                 |
|---------------|-------------------------------------------------------|
| Object        | true                                                  |
+-----------------------------------------------------------------------+
+8
source

The only number that is "falsey" (and therefore evaluates the value falseand does not pass the if statement) is equal 0. The rest are "true", even negative ones.

!!-1. . ! -1 false, true. .

+7

Truthy Falsy

:

  • 0 ()
  • "( )
  • NULL
  • undefined
  • NaN ( Not-a-Number!)

, " 0 "( )," false", (false ), , .

+3
source

As said, only 0 (including numbers) is equivalent to zero. But yes, there is a list of things that are false in javascript, and this:

  • Lying
  • Null
  • undefined
  • empty line ""
  • number 0
  • number NaN

everything else when comapred to false returns false. e.g. -1 == false → false

0
source

Source: https://habr.com/ru/post/1623092/


All Articles