Skip to content

Instantly share code, notes, and snippets.

@nw
Last active February 10, 2016 03:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nw/f256c6b9235c33df4d15 to your computer and use it in GitHub Desktop.
Save nw/f256c6b9235c33df4d15 to your computer and use it in GitHub Desktop.

Syntax

for ([initialization]; [condition]; [final-expression]) {
  statement
}

initialization

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.

final-expression

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.

statement

A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).

var array = [ 1, 2, 3 ],
len = array.length,
i = 0, // iterator initialize it to `0` index.
item; // initialize variable (used inside for loops)
// for expressions are broken into 3 parts: for( initalize, comparison, )
for(; i < len; i++) { // we can ignore the initializer since we already initialized above
console.log(i, array[i]);
}
for(i = 0; i < len; i++) { // reset i
console.log(i, array[i]);
}
for(i = 0; item = array[i]; i++) { // we can do the assignment inline. Note: this will not work on sparse arrays (arrays that have falsey values)
console.log(i, item);
}
i = 0; // reset i
for(; item = array[i++];) { // we can skip `final-expression` Note: does not work on sparse arrays
console.log(i, item);
}

Syntax

array.forEach(statement);

Very much like for loops but we get variable house cleaning for free. Where we normally define our for loop statement to apply to each item in the array. We use a function instead.

Our function has the signature (item, index). The function will be called for each item in the array. When it calls the function you supply it will pass the current item and index.

array.forEach(function(item, idx){
  console.log(idx, item); // outputs the same as above.
});

Remember we can change the parameter names to whatever we want them to be. It is the order of parameters that is important here.

array.forEach(function(number, i){
  console.log(i, number); // same exact thing, just different names.
});

We can pretty much recreate this behavior using a for loop.

function forEach(array, callback){
  var i = 0,
      length = array.length;
  for(; i < length; i++) {
    callback(array[i], i); // note we are calling the function that was passed in as the second argument and passing the current item and index.
  }
}

// Usage
var arr = [1,2,3];
var fn = function(item, index){ // what we want to do with a single item.
  console.log(index, item);
}

forEach(arr, fn);

Syntax

JQuery provides a helper function to loop over matching elements from our query.

var elements = $('*'); // match all elements;

elements.each(statement);

JQuery each is very similar to the native Array.forEach however for some reason jQuery changed the order of the function signature. Instead of passing the item first and index second, JQuery reverses the order.

elements.each(function(index, element){

});

I believe the main reason for this is because of the binding of this inside of the function.

elements.each(function(index, element){
   element === this; // true
});

The second parameter is redundant and can be ignored.

elements.each(function(index){
  console.log(index, this);
});

Rememeber that both this or the second arg are native DOM elements. They do not have the JQuery interface. If you want the JQuery behavior back inside of your function.

elements.each(function(index, element){
   var el = $(this);
   console.log(index, el.text()); // prints index and the current text value for that DOM node.
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment