“For loop” in JavaScript

Last week, a colleague of mine asked me “Why are you using a ‘standard for loop’ rather than the faster ‘for-in loop’ to loop through an Array in JavaScript?” and for this reason I’m going to write a short explanation about that. First of all, when I talk about the standard ”FOR loop”, I mean something like

for (var i=0; i < myArray.length; i++){
    // do something
}

instead the ”FOR-IN loop” is something like:

for (var i in myArray){
    // do something
}

for-in loop is faster…just to type, for a lazy developer like me and it’s a common mistake especially for developers coming from Java programming (I’m a Java developer as well, that’s why I know that :P), trying to port Java into JavaScript. The two main problems with for-in loop are :

  • It enumerates through all the properties even the ones associated to the Object (that can be augmented previously)
  • The order of the elements is not guaranteed.

Asynchronous javascript – Callback Hell

What is “callback hell“?

Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:

fs.readdir(source, function(err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function(filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function(err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function(width, widthIndex) {
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})

See all the instances of function and })? Eek! This is affectionately known as callback hell.

Introduction to Callbacks – Node.js

This is the most important topic to understand if you want to understand how to use node. Nearly everything in node uses callbacks. They weren’t invented by node, they are just part of the JavaScript language.

Callbacks are functions that are executed asynchronously, or at a later time. Instead of the code reading top to bottom procedurally, async programs may execute different functions at different times based on the order and speed that earlier functions like http requests or file system reads happen.

The difference can be confusing since determining if a function is asynchronous or not depends a lot on context. Here is a simple synchronous example, meaning you can read the code top to bottom just like a book:

var myNumber = 1
function addOne() { myNumber++ } // define the function
addOne() // run the function
console.log(myNumber) // logs out 2

JavaScript Module Pattern

The module pattern is a common JavaScript coding pattern. It’s generally well understood, but there are a number of advanced uses that have not gotten a lot of attention. In this article, I’ll review the basics and cover some truly remarkable advanced topics, including one which I think is original.

The Basics

We’ll start out with a simple overview of the module pattern, which has been well-known since Eric Miraglia (of YUI) first blogged about it a few years ago. If you’re already familiar with the module pattern, feel free to skip ahead to “Advanced Patterns”.