I'm using the following code to create a basic image rotation feature, & I want to get a better understanding of how it's working. I get most of it, but the line in the rotate function where it uses the 'strict' equals & the ternary operator, i.e. (i === (imgs.length -1) ) ? i=0 : i++ ;) is a bit confusing. I know it's incrementing the counter, but what's it doing before that?
var i, imgs, pic;
function rotate()
{
pic.src = imgs[i] ;
(i === (imgs.length -1) ) ? i=0 : i++ ;
setTimeout( rotate, 2500 );
}
function init()
{
pic = document.getElementById("pic");
imgs = [ 'images/shimano_offer.jpg', 'images/kids_bikes1.jpg', 'images/cycle_to_work.jpg' ] ;
var preload= new Array();
for( i=0; i< imgs.length; i++ )
{
preload[ i ] = new Image();
preload[ i ].src = imgs[ i ];
}
i=0;
rotate();
}
Code is from http://ineasysteps.com/products-page/all_books/javascript-in-easy-steps-4th-edition/
The line
(i === (imgs.length -1) ) ? i=0 : i++ ;
Could (and should) be written as:
if (i === (imgs.length - 1)) {
i = 0;
} else {
i += 1;
}
Yes, the former is less bytes, but much more difficult to understand and debug.
Edit: Norguard points out a valid way of using the ternary form for this. I use ternaries, but in this case I would not because I would likely want to put a breakpoint on the "i = 0" condition at some point when debugging. If you don't anticipate needing a breakpoint, his method is more compact and concise, and possibly preferable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With