-2

To check weather the element is exist or not I am using

   if($('#id').length)
       //statement 1
   else
      //statement 2

It is working fine for me. But statement1 will execute when the condition is true otherwise statement2 will execute. But how is it working when length is returning length (it is a number like 1 , 2...)

I thought if the length is 0, then it is taking false for 0. But what about remaining cases. I am unable to understand what is happening here. Thanks in advance...

Pete
  • 57,112
  • 28
  • 117
  • 166
PSR
  • 39,804
  • 41
  • 111
  • 151

4 Answers4

3

From the MDN on if :

Any value that is not undefined, null, 0, NaN, or the empty string (""), and any object, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement

This means that when the length is 1 (or greater but that can't happen for this selector) then it evaluates to true.

So when the element with id id is found, the statement 1 is executed. when the length is 0, then statement 2 is executed.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

Here's some output from the chrome console, that might help you:

> Boolean(1) //The number 1
true

> Boolean(0) //The number 0
false

> Boolean(0.0000000000000000000000000000000000000000001) //A very close to 0 float
true

> Boolean(0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001) //This is where it starts rounding down to zero
false

> Boolean(false) //A boolean "false"
false

> Boolean(NaN) //Not a number
false

> Boolean(undefined) //Undefined
false

> Boolean("") //An empty string
false

> Boolean(-3) //A negative number
true

> Boolean("string") //A string that is not empty
true

> Boolean([]) //An empty array
true

> Boolean({}) //An empty object
true

> Boolean(2.5) //A float
true

..hence, if length is 0 (as in; the element could not be found) then it does not evaluate to true and therefore chooses the } else { statement instead.

h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
0

Javascript has a concept of truthy/falsy where values like 0, false, undefined and null are considered to be falsy and others are considered to be truthy.

If if the length is 0 then it becomes falsy and the condition will fail, else if length !=0 then the value is considered to be truthy and the condition will succeed.

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
-1

Yes this is how javascript works

An explanation here

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

Community
  • 1
  • 1
ripu1581
  • 300
  • 1
  • 9