### JavaScript: Efficient For Loops

I’m a little bit behind the times, but I just ran across this video on YouTube from June 2009.  It’s a presentation by Nicholas Zakas, pricincipal front end engineer for Yahoo!.  Nicholas discusses a way to make loops significantly faster.

The traditional method of using a for loop looks like this:

for (var i = 0; i < 100; i++) {
// Do something
}

This can by simplified by turning it on it’s head and decrementing from the max value, rather than incrementing to the max value.

for (var i = 100; i—;) {
// Do something
}

This has the same result, but can be noticeably faster when working with large (very large) loops.

But why does it work?

In JavaScript, a 0 (zero) value can also be interpreted as a Boolean false.  As soon as i hits 0 JavaScript sees it as false and it breaks the loop.  Try it for yourself:

for (var i = 100; 0;) {
// Loop breaks immediately.  Does nothing
}

### Efficient Conditional Statements

Did you know that conditionals are evaluated in order and JavaScript is smart enough to stop evaluating them as soon as it is capable of determining the result?  For example, if you have a conditional that is checking several values…

if ( a && b && c ) {
// Do Something
}

If a is evaluated as false, it doesn’t even check b and c.  Here’s a little test to demonstrate it.

var a = 1;
var b = true;
if ( b && a++ ) {
// Do something
}
console.log(a);

In this case, b is true so it continues to evaluate a which is incremented.  After the statement we log a to show that is has indeed been incremented to 2.  Now try it again, except this time b is false

var a = 1;
var b = false;
if ( b && a++ ) {
// Do something
}
console.log(a);

This time b is evaluated as false so the conditional breaks immediately and a is not incremented.  When we get to the console log we still have a value of 1.  Neat, right?

Douglas Crockford, JavaScript guru, discusses the history, the good parts and the bad parts of JavaScript.  Great video!

I’m trying out the new Spotify Play Button.

### Creating a Scrolling Overflow for iOS

We seem to run into a problem when creating an element that has an attribute of `overflow: auto` or `overflow: scroll`. It works fine in the browser, but upon testing it on an iPad the box will not scroll.

The reasoning behind this is solid. The same mechanic (swiping your finger across the screen) would be used to scroll the element and pan the page.  Apple chose to take the consistent route and a swipe pans the page, but now there is no way to scroll.

Enter the `-webkit-overflow-scrolling` attribute.  This attribute is supported starting with iOS 5 and can take a value of `touch`.  Adding this attribute to any element that could scroll in a desktop-based browser can now also be scrolled by swiping over the box.