In the following code
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
the part '$active.next().length' doesn't seem to pare 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?
In the following code
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
the part '$active.next().length' doesn't seem to pare 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?
Share Improve this question asked May 1, 2012 at 17:01 Simon SuhSimon Suh 10.9k28 gold badges90 silver badges119 bronze badges 2- you might wanna read this: stackoverflow./questions/6766044/… – Martin Jespersen Commented May 1, 2012 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 Commented May 1, 2012 at 17:12
5 Answers
Reset to default 11In javascript any expression can be converted to a truthy or falsy value and hence is valid in a parison 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
If the length
property is equal to 0
or undefined
(i.e. $active
is not an array), the condition will be false
.
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
.
It's a ternary parison 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.
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');
}