6

In the following code

var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

the part '$active.next().length' doesn't seem to compare anything and I don't understand how the condition is determined to be True or False.

Or is it saying that: if the various $next is equal to $active.next().length then the condition is true?

Simon Suh
  • 10,599
  • 25
  • 86
  • 110
  • you might wanna read this: http://stackoverflow.com/questions/6766044/understanding-javascript-hoisting-and-truthy-falsy – Martin Jespersen May 01 '12 at 17:06
  • A funkier (and shorter and less function calls) way of doing this would be var $next = $($active.next()[0] || '#slideshow img:first'); – GillesC May 01 '12 at 17:12

5 Answers5

11

In javascript any expression can be converted to a truthy or falsy value and hence is valid in a comparison place. The values which are false in javascript are

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

In this case length refers to a numeric value and if it evaluates to 0 then it will be considered falsy. Otherwise it will be truthy

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
5

If the length property is equal to 0 or undefined (i.e. $active is not an array), the condition will be false.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
2

If $active.next().length is true, which means that there is a next element, then $next = $active.next(). Otherwise $next = $('#slideshow IMG:first'). The ? operator is called the ternary operator. It is a short if else.

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
1

It's a ternary comparison equivalent to:

if($active.next().length) {
    $next = $active.next();
}
else {
    $next = $('#slideshow IMG:first');
}

So the condition is based on $active.next().length which should return a value of zero or greater. Anything greater than zero, JavaScript will interpret as true, zero false.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

What you're looking at a Ternary opertation which is a short hand for If... Else... has you mentioned in the title.

So the long version of your statement is;

if($active.next().length){
 $next = $active.next();
}else {
 $next = $('#slideshow IMG:first');
}
Simon
  • 37,815
  • 2
  • 34
  • 27