Super Flexible JavaScript Object and Array Iteration with jQuery.each()

jQuery

jQuery LogoThe jQuery.each() method makes it trivial to iterate over or inspect any kind of collection: arrays, objects, array-like objects, even jQuery DOM Objects.

Working with JavaScript means working with Objects. There is almost no way around this. So even in the simplest of scenarios, at some point you are likely to encounter an object and you need to inspect it.

Keep in mind that in JavaScript, there are different kinds of objects. For example, an array is an object. And, a DOM element is an object. It’s no secret that I am a huge fan of the JavaScript “For/In” loop. If you are not able to use jQuery then that is your go-to tool for object inspection. If you are using jQuery, then the static .each() method is a real winner.

It is important to make sure you understand that this is not the same thing as the $().each() method. When you pass a CSS selector to jQuery and then call the .each() method on the collection that is returned, you are calling a different method in jQuery. It is very similar, but that syntax is meant especially for DOM collections.

The jQuery.each() method is a static method of the jQuery object. It is a more generalized method that can be used to iterate over any object, array or array-like object. So the syntax is quite simple:

The OBJECT argument is any object, array or array-like object. The CALLBACK argument can be an inline anonymous function, a named function expression or a variable that points to an anonymous function.

Example # 1

 

In Example # 1, we have provided a simple array: three strings, each representing a corresponding day of the work week. The callback function executes for each one of the array elements, and inside of that function the variable “value” represents the value of that array element. We could have called that variable “baseball”; it doesn’t matter what you call it. The most important thing to remember is that the second argument to the callback will return the value of the current array element that is being iterated over. So, simple stuff.

Here is a JSBin link for Example # 1: http://jsbin.com/epanov/1/edit

 

Example # 2

In Example # 2, we take advantage of the “index” argument. In the console, we output the value of that variable. Again, this variable can be named anything. As with “value”, it’s most important to be aware that the first argument of the callback will return the index of the array element that is currently being iterated over.

Here is a JSBin link for Example # 2: http://jsbin.com/epezuc/1/edit

 

Example # 3

In Example # 3, we take things a step further to illustrate the fact that we can not only access the value of the current array element, but we can do things with it. Here, we simply remove ‘day’ from the string. But there is certainly a whole lot more that one might do. For example, if these array elements were objects instead of primitive strings, we could make changes to the objects and the next person or function who reached for that object would find it changed.

Here is a JSBin link for Example # 3: http://jsbin.com/okoxej/1/edit

 

Example # 4

In Example # 4, we move the object out of the jQuery.each() call and then simply reference it as the variable “data”. This time we have provided an array of objects. So on each iteration of the callback, instead of simply outputting a string, we are inspecting an object.

Here is a JSBin link for Example # 4: http://jsbin.com/usewoj/1/edit

 

Example # 5

In Example # 5, things get even more interesting. Here, we can see the brilliance of the jQuery.each() method. In this case we provide an object literal as the first argument to the .each() method. When an object is passed in, then the value of the “index” variable will be the name of the key or property of the object. So this saves you the time it would take to roll your own “For/In” loop.

Here is a JSBin link for Example # 5: http://jsbin.com/examuz/1/edit

 

Example # 6

In Example # 6, the object that is provided is a jQuery collection object. So now, on each execution of the callback, we can use $(this) to reference the jQuery DOM element object that is being iterated over, and of course do all the usual kinds of fun things to the element with jQuery.

Here is a JSFiddle link for Example # 6: http://jsfiddle.net/n7PRD/

 

Example # 7

And here, in Example # 7, we have abstracted the callback. Instead of providing an inline anonymous function, we provide a reference to a variable that is a function: “inspect”. So, that function will be called for every element provided in the data. The data we have provided in an array, and each element of that array is an object with some user account data. Phew! So, on each iteration of the callback (which is really the variable “inspect”, which is a function), we output the contents of that object to the console. We certainly could have done much more here, but the point of the example is that you can abstract any aspect of this that you like. So, as you can see, there is a ton of flexibility here and you are only limited by your imagination.

Here is a JSBin link for Example # 7: http://jsbin.com/iriwer/1/edit

 

Summary

In this article we learned a bit about the jQuery.each() method. We discussed the simple syntax, as well as the two arguments that are used in the callback. We also explored multiple scenarios such as inspecting an array of strings, inspecting an array of objects, inspecting objects and inspecting jQuery DOM objects.

Helpful Links for the jQuery.each() Method.

http://api.jquery.com/jQuery.each/

http://www.jquery4u.com/jquery-functions/jquery-each-examples/

http://stackoverflow.com/questions/722815/jquery-each-practical-uses

Two Ways to Dynamically Append an Element to a JavaScript Array

JavaScript

JavaScript Logo - dynamically appendThere are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array.prototype.push() method, or you can leverage the array’s “length” property to dynamically get the index of what would be the new element’s position.

I have provided candidate pre-screening services for recruiters in the past, and one of the classic JavaScript interview questions is: “Name two ways to dynamically append an element to a JavaScript array.” Some folks nail that question, but some are left scratching their heads. So I thought I’d quickly re-visit the logic behind this concept.

At first glance, some might say: “Well, you are the programmer. So you know how long the array is and can dynamically append an element by doing the following: foo[x] = newElement. Right?” Well, yes, but that is not what we are really trying to do.

Why Dynamically Append an Element to a JavaScript Array ?

I think that most programmers will agree that what you want in this situation is to be able to add an element to the array, regardless of the length. What you want to assume is that you will not know the length. And from a pseudo-code perspective, you want to say: “Hey, I have an array named ‘foo’ and however long it is, add this new element named ‘newElement’ to the end of it.” I think that when you can accomplish that, you have significantly more power.

Array.prototype.push() – Example # 1

In Example # 1, we used JavaScript’s Array.prototype.push() method. This wonderful little utility adds whatever you pass it to the end of the array.

The syntax is: yourArray.push(WhatYouWantToAdd)

It’s literally that simple.

Using the array’s “length” property – Example # 2

In Example #2, we leverage the “length” property of the array. The reason this works so well is that the value of an array’s “length” property will always be exactly one higher than the index of the last element in the array. Why? Because while array indexes are zero-based (i.e. the first element in the array is element 0, and the second element in the array is element # 1, and the third element is element # 2, etc…), the array’s “length’”property is a one-based value (i.e., if there are three elements in the array, the length is: 3).

So, if the array “foo” has three elements, foo[2] is the last element in the array, and the value of foo’s “length” property is “3”. Therefore, foo[3] does not exist yet (remember foo[2] is the last element).

Since we may not always know the length of the array when we need to dynamically append an element by simply adding a new element to the end, we can reference foo[.foo.length]. This way, no matter how many elements are in foo, we can simply assign the new element to foo[.foo.length].

Helpful Links for JavaScript Arrays

JavaScript for Beginners | Arrays: Adding and Removing Elements

JavaScript Array Management with Push(), Pop(), Shift() and Unshift()

Why is a JavaScript Array’s Length Property Always One Higher Than the Value of the Last Element’s Index?

Summary

There are two ways to dynamically append an element to the end of a JavaScript array. You can use the Array.prototype.push() method, or assign the new variable to the index that is equal to the array’s “length” method.

Associative Arrays in JavaScript

JavaScript

JavaScript LogoYou may be finding conflicting information about associative arrays in JavaScript. Well, the answer is quite simple… and then things start to get a little odd

If you are frustrated because you have been getting different answers on this subject, I”ve got good news and bad news. The good news is, the answer is simple: associative arrays are not supported in JavaScript. Arrays in JavaScript are index-based. Plain and simple, end of conversation. But the bad new is, it’s not quite the end of the conversation. The reason for this is that the following code actually works just fine:

[insert shrugged shoulders here]  “…ok Kevin, so what’s the problem ?

The problem is: you do not have an array with five elements. You have an array with three elements, and two properties.

Huh?

Yup, this is the part where JavaScript array objects behave in an unexpected way. But hang in there, it’s actually kind of cool once you understand what is happening.

Arrays are Objects

Arrays in JavaScript are numerically indexed: each array element’s “key” is its numeric index. So, in a way, each element is anonymous. This is because when you use methods of the Array object such as array.shift() or array.unshift(), each element’s index changes. So, after using array.shift(), array element # 2 becomes array element # 1, and so on. (array.pop() and array.push() may change the length of the array, but they don’t change the existing array element’s index numbers because you are dealing with the end of the array.)

All this is to say that in a JavaScript array, each element can only be identified by an index, which will always be a number, and you always have to assume that this number can change, which means that the whole “key/value” idea is out the window (i.e. no associative arrays in JavaScript. Sorry.).

OK smarty-pants, if you can’t have associative arrays in JavaScript, why does this work: arr[“drink”] = “beer” ?

Glad you asked. This is because in JavaScript, arrays inherit from Object(). Whether you use an array literal or instantiate the array constructor, you are creating an object, plain and simple. Consider the following:

Example # 1

In Example # 1, we create an array in three different ways. The first line creates a new array with three elements, but they are all undefined. The second line creates a new array, but it is empty, with no elements (this is an array literal). The third line creates an array literal, but we provide values for the elements as we define the array. In all three cases, you are creating an instance of the Array() constructor, which inherits from Object(). So, these are ALL objects.

Example # 2:

 

In Example # 2, we create an array literal, but it is empty. (var arr = []; works just fine, but it is an empty array.) When we check the length property and try to inspect the object with console.dir(arr), we can clearly see that it is empty. Then we add elements to the array, and add named properties (e.g. arr[“drink”] = “beer”). But when checking the array’s length property, and inspecting the object, we can see that the actual “array” part of the array still has only three elements (i.e. “music” and “drink” are NOT elements in the array), and that “music” and “drink” are properties of the array object.

Arrays are Objects with their own special “array-ish” properties

What is happening, is that the Array() constructor returns an instance object that has some special members that other objects such as Function() and Date() do not. So when your code says:  arr[“drink”] = “beer” you are simply adding a new property to your object, which happens to be an array, and that property has a name of “drink”, and you have assigned the value of “beer” to it.

You could have easily assigned a number, an object, an anonymous function, or one of JavaScript’s other data types. This property “drink” has no connection to the elements in the array. It does not increase the value of the array’s “length” property, and it cannot be accessed via the array-ish methods such as pop() or shift().

Let’s see what happens when we take advantage of this object’s “array-ness.”

Example # 3:

OK, so things are gettin’ pretty weird, right? Yep, but it’s all cool stuff, and at the end of the day, it’s no big deal. It just illustrates the way objects work in JavaScript. Let’s run it down:

  • First, we use the JavaScrpt Array() object’s push() method to dynamically add an element to the array. It just so happens that this new element is an object literal, with two properties. Its index becomes 3.
  • Next, we use the same push() method to dynamically add another element to the array. This new element is an anonymous function. Its index becomes 4.
  • Next, we create a new property for our array called “testMe”. This new property happens to be an anonymous function. It has NO index, because it is NOT an element in the array, just a new property that we have added.
  • Next, we use the console to check the array’s length property, which is now “5”, and we inspect it.
  •  Dont’ forget it is an array, but it is also sill an object; Array() inherits from Object(). When inspecting the object, we see that our two uses of push() did, in fact, add two new elements to the array; one is an object, the other is an anonymous function. We also have “testMe”, wich is a new property of arr.
Ok, so what happens if we attempt to access the two functions that we added? Oh, they will run just fine, but remember: one is an element in the array, the other is a property of the arr object. So we access them differently:

Example # 4:

The output for Example # 4 would be:

In each case, we are simply executing a function. It’s just that in the first case, that function is an element in the “arr” array. So, we have to access it using its index, which happens to be “4”. This can get tricky fast, and care should be taken in doing this kind of thing, but just to illustrate a point: array elements in JavaScript can be of any data type. In the second case, we access the function by its name “testMe”, because it is a PROPERTY of the array, not an element. Much easier, and there are no issues, because “testMe” will always be “testMe”, so it’s easy to access.

Summary

This is all pretty overboard. I mean, don’t we usually want this: var arr = [“mon”,”tues”,”wed”] ? Well, yes. Most of the time we do. But the point of this post is two-fold:

  1. JavaScript does NOT support associative arrays. Period.
  2. Arrays are objects, so properties can be added any time. Those properties can be any data type.

In JavaScript, arrays are best used as arrays, i.e., numerically indexed lists. The great thing is that those elements in the array can be of any data type. Index # 0 can be a string, # 1 can be an object, # 2 can be an anonymous function, and # 3 can be another array.

But once you start doing things like this: arr[“drink”] = “beer”, you are swimming in somewhat dangerous waters. Unless you really know what you are doing, you will get odd behavior because arr[“drink”] is NOT a numerically indexed “member” of the array (it is not an array “element”), and does NOT have the relation to arr[0] and arr[1] that you may think it does.

As soon as you start doing things like: arr[“drink”] = “beer”, it is time to consider putting this key-value pair in an object literal. You don’t have to, but it’s a better way to manage your data, and the approach leverages JavaScript’s strengths, instead of wrestling with the somewhat odd nature of it’s underlying architecture.

P.S.: If you really wanna see some odd JavaScript array behavior, try this:

The strange output of this one is for another discussion : – )

Helpful links for associative arrays in JavaScript

JavaScript Interview Questions: Arrays

JavaScript

Q 1: Name two ways to dynamically add the value “bar” to the array “foo”

A:

Hint: Two Ways to Dynamically Append an Element to a JavaScript Arrayy


Q 2: Of what JavaScript type is an Array?

A: object

Hint: Associative Arrays in JavaScript


Q 3: What property tells you the length of a JavaScript array?

A: The “length” property

More Info on the JavaScript Array’s “length” property:

Why is a JavaScript Array’s Length Property Always One Higher Than the Value of the Last Element’s Index?


Q 4: If the array “foo” has a length of 10, what is the index of the first element in the array?

A: 0

Hint: JavaScript Arrays are zero-based


Q 5: If the array “foo” has a length of 10, what is the index of the last element in the array?

A: 9

Hint: JavaScript Arrays are zero-based


Q 6: What is the syntax you would use to assign the first element in the array “foo” to the variable “bar”?

A:


Q 7: True of False: An element in a JavaScript array can be another array

A: True

Hint: JavaScript Array elements can be arrays


Q 8: Given the following line of code, what is the length of the array “foo”?

A: 0

Hint: foo is an Array literal, but in this line of code, no elements have been defined.


Q 9: What does the array.shift() method do, and what does it return?

A: It removes the first element from the array and returns that element

More info on the JavaScript array.shift() method:

JavaScript Array Management with Push(), Pop(), Shift() and Unshift()/a>


Q 10: Given the following line of code, what would be the output of the console?

A:  [undefined, undefined, undefined]

Hint: When you instantiate the JavaScript Array() constructor, and pass in a single number, that number will indicate the length of the array, but the elements are still not initialized (i.e. they are all undefined)


Helpful Links for JavaScript Arrays

Kevin Chisholm – YouTube: Array

Kevin Chisholm Blog – Array

Why is a JavaScript Array Length Property Always One Higher Than the Value of the Last Element’s Index?

JavaScript

JavaScript Logo - Array Length

The “length” property of a JavaScript array is a very helpful tool, but why is array length
always one “off”?

Arrays in JavaScript are zero-based. This means that JavaScript starts counting from zero when it indexes an array. In other words, the index value of the first element in the array is “0” and the index value of the second element is “1”, the third element’s index value is “2”, and so on. This is not unusual in computer programming languages. The JavaScript array length property is given in a one-based context. So, a JavaScript array with one element will have a “length” of “1”. If a JavaScript array has four elements, then that array’s “length” property will have a value of “four”. But (and here is the point where many get confused), if a JavaScript array has four elements, the last element has an index of “3”. This is because, again, JavaScript arrays are zero-based.

The Array Length – Example # 1

In Example # 1, we have an array with five elements. The console.log() statement reflects this as well because the “length” property of this array is “5” (i.e. this is a one-based value).

So, even though the array has a length of 5, the first element has an index of 0, and the last element (the 5th element) has an index of 4. Now this is the most important point, and it’s what explains the “off” reference: the length of the array is always one higher than the index of the last array element because the array indexes are zero-based, but the length property is one-based.

One Less Than the Length – Example # 2

In Example # 2, we create a variable who’s value is one LESS than the length of our array. So, since our array’s “length” property is “5”, our “len” variable is equal to “4”. Our loop will start at 0, and run until it equals “4”. This IS five iterations, but we are starting at 0, not one. So, since JavaScript starts counting Arrays from Zero, our code successfully outputs the value of each element in the array.

This is a very common technique: when you want to iterate an array, you create a for-loop, and set the max iterations to “one less than” the length of the array. Now while this may seem tedious, it’s actually a rock-solid pattern to follow, because the array’s length will always (always) be one higher than the index of the last element in the array. So, it follows that if your loop iterates X times, and X equals “one less than” the length of the array, then your loop will always iterate over every element in the array. This takes a little getting used to, but once you do, it becomes second nature.

Console Output – Example # 3

Summary

JavaScript arrays are zero-based. The JavaScript array “length” property returns the number of elements in an array, but it is a one-based value. So whenever you want to use the “length” property to say “hey, start from the first element in an array and go until you reach the last element,” start from zero, and go until you reach the array’s “length” property value, but “minus one!”

Helpful Links for JavaScript Arrays

JavaScript Array Management with Push(), Pop(), Shift() and Unshift()

Two Ways to Dynamically Append an Element to a JavaScript Array

Executing an Array of JavaScript Functions Using the shift() method

JavaScript

JavaScript Logo

Sometimes you have multiple JavaScript functions that you need to execute in a specific order, but do not know the details ahead of time

Both jQuery and Dojo offer their own flavor of “Deferred” functionality. This is a pretty deep topic that, while a bit challenging, offers tremendous power with respect to queuing up an invocation of multiple functions in an orderly manner. One concept that plays into this way of thinking is using the JavaScript array object’s shift() method. It easily fires off some functions in order, even when you don’t know ahead of time how many there will be.

Example # 1

var b = function(){ console.log(“this is function: b”) } var c = function(){ console.log(“this is function: c”) } var foo = [a,b,c]; while (foo.length){ foo.shift().call(); }

In example # 1, we define three functions. Then, we build an array with each element being a reference to one of our functions.  Now, using a while loop, we call each function. There is a cool interplay going on here. For the while loop, as long as foo has length (that is as long as the length of foo does not return a “falsy” value, such as zero), the loop will run. Inside the loop, the JavaScript shift() method not only removes the first element from the array, it also returns that element. So, we chain onto that return value, which is the function itself, and use the JavaScript .call() method, to actually invoke the function. With each iteration of the while loop, the array looses an element. It therefore becomes smaller and smaller until finally,  “foo.length” returns zero, which is “falsy,” and the loop no longer runs.

The end result here is that you can have a list of functions that you can execute, one at a time, in a specified order, and each function runs only once.  A much more practical use for this technique is when you are adding methods to the array (i.e. our “queue”), at run time. You don’t know how many you might add, or what they might do, but you know that you can line ’em up, and fire ’em off!

Summary

Because so much of what the Front End Web Developer deals with happens in the life of a page, there are many circumstances in which you are not sure how many of something will come along. But if you are able to get your hands around such dynamic events, you can handle some pretty cools scenarios. Invoking an unknown number of functions at runtime is such a case. This technique provides a fairly simple way to implement this approach.

Helpful links for the JavaScript Array Object’s shift() Method

http://www.w3schools.com/js/js_obj_array.asp

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift

http://www.bennadel.com/blog/1796-Javascript-Array-Methods-Unshift-Shift-Push-And-Pop-.htm

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/shiftMethod.htm