Getting to Know the JavaScript element.classList Object

Object-Oriented JavaScript

JavaScript LogoNative JavaScript provides a way to access and manipulate all of the CSS classes that are assigned to an HTML element.

The JavaScript element.classList object is an instance of the JavaScript DOMTokenList object. It exposes one property and a number of methods that allow you to work with CSS classes that are assigned to an HTML element.

While it has been supported for some time by all major browsers, Microsoft Internet Explorer has, unfortunately, ignored JavaScript’s element.classList object until very recently (what a big surprise). If you need to support IE9 and below (and of course you do), then all bets are off. Bummer. That said, this object is nonetheless a super-helpful feature that makes CSS class manipulation a snap.

But what about jQuery?

There is no doubt that the jQuery methods hasClass(), addClass(), removeClass() and toggleClass() are all fantastic, but there ain’t nothin’ goin’ on under the hood that you can’t do yourself. And what is under the hood is tedious stuff like this:

This kind of code will soon join the ranks of the eight-track cassette and pagers. While that is the current reality of cross-browser CSS class list manipulation, the fact is that native JavaScript is always evolving, and as soon as Internet Explorer 10 becomes the IE standard, the JavaScript element.classList object will be yet another native JS tool to tuck into your belt.

The length Property

Even though the element.classList object is not an array, it is “array-like” in that it has a “length” property, and each CSS class name is represented by a numerically indexed property whose value is the name of that class (a string). This is super-helpful if you want to enumerate the classes that are members of this object. You could certainly grab an individual member’s value using bracket-notation: element.classList[0], a “for” loop, or the item() method, which is discussed next.

The JsFiddle link below demonstrates the classList object’s length property. The class “bar” is toggled when you click the element specified. On each click, the classList object’s length property is shown. Since a class is toggled, that length value changes with each click, which helps to demonstrate the dynamic nature of this property. Keep in mind that like any JavaScript array, the length property’s value will always be one higher than the index of the last element.

Here is the JsFiddle.net link for the classList object’s “length” property : http://jsfiddle.net/BmFZc/

The item() Method

The item() method allows you to reference a specific class name in the collection of class names. When you pass an integer to this method, it returns a string representation of the class name that matches that index. So keep in mind that this collection is zero-based. In the first JsFiddle link below, we manually reference a number of classes in the class list, using the item() method. In the second JsFiddle link below, we use a “for” loop to accomplish the same task.

Here is the JsFiddle.net link for the item() method: http://jsfiddle.net/N88x9/

Here is a second JsFiddle.net link for the item() method: http://jsfiddle.net/WE7gc/

The add() method

As you might expect, the add() method adds a class to the element’s class list. In the JsFiddle link below, you can see that the class “bar” is added to the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the add() method: http://jsfiddle.net/uzMAx/

The remove() Method

In the manner opposite to the add() method, the remove() method removes the specified class from the element’s class list. Much like the example for the add() method, you can see that the class “bar” is removed from the element’s class list because the element’s appearance changes dramatically, as per the CSS that is specified.

Here is the JsFiddle.net link for the remove() method: http://jsfiddle.net/4h7m4/

The toggle() Method

The toggle() method will check to see if the element already has the specified class. If not, then it adds the class. If it does have the class, then it removes it. Depending on the scenario, this can minimize redundant code.

Here is the JsFiddle.net link for the toggle() method: http://jsfiddle.net/wWfNf/

The contains() Method

You can check to see if an element already has a class by using the contains() method. When you pass it a string name representing the class that you would like to check for, it returns true or false, indicating whether or not the element has the class you provided.

Here is the JsFiddle.net link for the contains() method: http://jsfiddle.net/wWfNf/

The toString() Method

The toString() Method simply returns a space-separated list of the classes that are applied to that element.

Here is the JsFiddle.net link for the toString() method: http://jsfiddle.net/GqzD5/

Summary

In this article we learned about JavaScript’s element.classList object. We demonstrated that while not exactly a JavaScript array, it is an “array-like” object with a length property, and some useful methods that allow you to work with the CSS classes that are assigned to an HTML element.

Helpful Links for the JavaScript element.classList object

https://developer.mozilla.org/en-US/docs/Web/API/element.classList

http://blog.alexanderdickson.com/manipulating-classes-with-javascript

http://tiffanybbrown.com/2011/08/15/class-manipulation-with-classlist/

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

Arrays

JavaScript LogoWhen you need to work with the first or last elements in a JavaScript array, the push(), pop(), shift() and unshift() methods are usually the best way to go.

Programmers who are new to JavaScript or come to it via languages such as PHP may find arrays a bit limiting. The main issue is usually the fact that in JavaScript, there are no associative arrays. While that may seem frustrating, associative array-like functionality can be achieved by leveraging the power and simplicity of objects. Although JavaScript arrays are restricted to numeric-based property names, they are otherwise quite flexible.

Since JavaScript array elements must have numeric property names, they are essentially anonymous. From a programmatic standpoint, the only array elements that you absolutely know anything about are the first and last elements in the array. And when an array has only one element, the first and last elements are one in the same.

The JavaScript Array object provides four very useful methods: push(), pop(), shift() and unshift(). To be precise, these methods belong to the Array object’s prototype property. We know this because every array you create shares a copy of these four methods (that is because every array you create is an instance of the Array constructor).

These four methods allow us to programmatically work with the only two elements of an array that we can be sure about: the beginning and the end. Every element between the first and last is a mystery to us because, from a purely programmatic standpoint, we have no idea how many there are or what they are. We only know that as long as an array has at least one element, it has a first and last element.

The JavaScript Array.push() Method

The JavaScript Array.push() method adds a new element to the end of the array. When doing so, the array’s length property increases by one. After adding the new element to the end of the array, this method returns the new length of the array.

Example # 1

In Example # 1, our array starts out with three elements. The first console.dir() call allows you to inspect it in your console and see that it contains only: ‘mon‘,’tues‘,’wed‘. We then use the Array object’s push() method to add a new element to the end of the array (“thurs”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the push() method has returned the new length of the array: 4. Then, another console.dir() call allows us to inspect the array, demonstrating that “thurs” was, in fact, added to the end of the array.

Here is the JsFiddle.net link for Example # 1: http://jsfiddle.net/4EHkp/

The JavaScript Array.pop() Method

The JavaScript Array.pop() method removes the last element from the end of the array. When doing so, the array’s length property decreases by one. After removing the last element from the end of the array, this method returns the array element that was removed.

Example # 2

In Example # 2, our array starts out with three elements. We then use the Array object’s pop() method to remove the last element from the end of the array (“wed”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the pop() method has returned the element that was removed from the end, which in this case is “wed”. Then, another console.dir() call allows us to inspect the array, demonstrating that “wed” was in-fact removed from the end of the array.

Here is the JsFiddle.net link for Example # 2: http://jsfiddle.net/VpJmu/

The JavaScript Array.shift() Method

The JavaScript Array.shift() method removes the first element from the beginning of the array. When doing so, the array’s length property decreases by one. After removing the first element from the beginning of the array, this method returns the array element that was removed.

Example # 3

In Example # 3, our array starts out with three elements. We then use the Array object’s shift() method to remove the first element from the beginning of the array (“mon”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the shift() method has returned the element that was removed from the beginning, which in this case is “mon”. Then, another console.dir() call allows us to inspect the array, demonstrating that “mon” was, in fact, removed from the beginning of the array.

The JavaScript Array.unshift() Method

The JavaScript Array.unshift() method adds a new element to the beginning of the array. When doing so, the array’s length property increases by one. After adding the new element to the beginning of the array, this method returns the new length of the array.

Example # 4

In Example # 4, our array starts out with three elements. The first console.dir() call allows you to inspect it in your console and see that it contains only: ‘mon’,’tues’,’wed’. We then use the Array object’s unshift() method to add a new element to the beginning of the array (“sun”). Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the unshift() method has returned the new length of the array: 4. Then, another console.dir() call allows us to inspect the array, demonstrating that “sun” was, in fact, added to the beginning of the array.

Summary

In this article, we learned about the JavaScript Array’s push(), pop(), shift() and unshift() methods. We also learned that all JavaScript arrays can leverage these methods to work programmatically with the beginning and end of the array, regardless of how many elements are in between. Additionally, we learned that in two cases, the new length of the array is returned, and in the other two cases, the element that was removed is returned.

Helpful Links for the JavaScript Array’s push(), pop(), shift() and unshift() methods

push()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

http://msdn.microsoft.com/en-us/library/ie/6d0cbb1w(v=vs.94).aspx

pop()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

http://msdn.microsoft.com/en-us/library/ie/hx9fbx10(v=vs.94).aspx

shift()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

http://msdn.microsoft.com/en-us/library/ie/9e7b4w20(v=vs.94).aspx

unshift()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

http://msdn.microsoft.com/en-us/library/ie/ezk94dwt(v=vs.94).aspx

Organize Your JavaScript Console Logging with a Custom debug() Function

JavaScript

JavaScript LogoEvery console.log() line in your JavaScript code has to be removed before pushing to production. With your own custom debug() method, you can safely leave all of your debug code in-place and just switch them “off” before going live.

The JavaScript console is an invaluable asset in the never-ending quest for sufficiently-tested code. For most JavaScript developers, a day at the office would not be complete without at least a few lines of debug code such as these:

But the problem is that code needs to be removed. That’s fine if it’s just a quick test. But what if there are 20 places in your code where you need to keep track of a value, trace program flow and logic, or test the return value of a function?” Well, that’s a lot of temporary code to keep track of and remember to delete. Even more frustrating is that in a month or two, when business wants more changes, you’ll probably wind up writing the same kinds of debug messages and putting them in the same places, only to have to search your script for “console” once again so that you can remove all of these debug statements before pushing to production.

There is certainly more than one way to skin a cat here, but a simple approach is to write your own custom debug function that shows messages, and knows when it should suppress those messages (i.e. when your code is running in production).

Creating a Custom Debug Function

First, let’s create a couple of functions that do things to objects. We’ll want to debug this code so that along the way, we can check to make sure that the functions are in-fact returning the object that is expected (combineObjects), or making the changes to the object that we pass in (arrayToUpper).

Example # 1

In Example # 1, we have created two simple objects. Let’s imagine that they were created separately somewhere else in our code, and need to be merged in order to create one complete “customer object”. We also have an array that contains the five days of the work week. This array has no functional relation to the two objects. The are all just variables that we can use to test our code.

The combineObjects() function takes two objects as arguments and returns a new object that contains the combined properties of the two original objects. The arrayToUpper() function takes an array as an argument and converts its string elements to upper-case.

For the sake of simplicity, I did not bother doing any kind of verification or type-checking in either method. In the real world, I highly recommend that these kinds of methods contain some kind of verification code at the top so that they fail gracefully.

For example, what if we passed two arrays to combineObjects()? Or what if arrayToUpper() received an array of functions as an argument? This is messy business. I’ve provided a few suggestion on how to create that kind of functionality in an earlier blog post: Validating JavaScript Function Arguments.

So, when you run Example # 1 in your JavaScript console, you will see that we have in-fact created a new object that is the sum of Obj1 and Obj2, and we have changed the array “myArr” so that all of its elements are now uppercase strings. But what I don’t like is that we have written two lines of “test” code that need to be removed at some point (i.e. the two console.dir() statements). I would like to include the testing in our functions so that we can simply call each function, not writing any special code that we need to keep track of and then delete before the production rollout.

Here is the JsFiddle.net link for Exampe # 1: http://jsfiddle.net/UnbVg/

Example # 2

In Example # 2, we have created a variable named “debugMode”. This tells our custom debug function whether or not messages should be output. If “debugMode” is set to “false”, then our custom debug function simply does nothing.

Ok, let’s look at our new “myDebug()” function. This function takes two arguments: a message and a callback. The message should be a string and if so, it will be output in the console. I tend to imagine messages such as “function getAccount started…” or “AJAX success callback fired….” etc. These are messages that your code can send to help “tell a story.”

The purpose of the callback is to allow for more complex messages. For example, you may want to inspect an object at that very moment. So, in addition to the text message, you can pass an anonymous function that contains a line such as “console.dir(myData)”. You could even include your “myDebug()” call inside of a “for” loop, inspecting the state of an object on each iteration of the loop. The sky’s the limit here. In general, I tend to feel that the text message and optional callback are enough for you to provide useful debugging messages for your app.

Example # 3 A

In Example # 3A, we have implemented our custom debug function: “myDebug”. Now we can simply call the functions combineObjects() and arrayToUpper() the way we normally would in our code. The “debugging” code that examines values and outputs informative messages now exists in the actual functions that do the work. When it is time to push this code to production, simply change the value of “debugMode” to “false”, and away we go. One line of code is all it takes to suppress all of our debug messages (see example # 3B below for a demonstration of this).

Here is the JsFiddle.net link for Example # 3A: http://jsfiddle.net/UnbVg/1/

Example # 3B:

In Example # 3B, we have set “debugMode” to “false”, which means that you do not see any debug messages. But to complete our proof-of-concept, we add two console.dir() statements to the end of our code, which demonstrates that the code once again, performed as expected and our custom debug method “myDebug” behaved exactly as designed: no console messages.

Here is the JsFiddle.net link for Example # 3B: http://jsfiddle.net/UnbVg/2/

Summary

In this article, we learned how to create a custom debug function. We discussed the value of minimizing “special” testing code that needs to be tracked and then removed before deploying to production. We also discussed how to design our custom debug function so that it can output text messages as well as execute anonymous functions. We also covered how to implement a very simple “off” switch. This will suppress any debug messages, which is recommended when pushing your code to production.

How to Turn the Query String Into a JavaScript Object

Object-Oriented JavaScript

JavaScript LogoIt is fairly common for any front-end web developer to examine the query string. If jQuery has taught us anything, that would be the power of abstraction: create functionality once, and then use that functionality as a tool over and over, as needed.

When working with the query string, it is usually best to grab it once, and then be done with that task. This will prove substantially helpful if you need to refer to the query string more than once in your code. If we do the work once, and do it right, then we have created a nice little tool that we can use over and over throughout our code.

So perhaps the best way to accomplish this task is to turn the query string into a JavaScript object. Simple stuff here. Let’s lay out our plan of attack:

  1. Get a reference to the Query String
  2. Chop off the question mark (we don’t need that)
  3. Turn the key/values into elements of an array
  4. Turn each key/value pair into a little two-element array
  5. Populate our object with each key/value as a propertyName / propertyValue
  6. We’re done!

So okay, let’s get to work.

Example # 1

In Example # 1 we have the raw and basic code needed to accomplish our task. I won’t go into any detail here. I just wanted to illustrate that the actual code needed is fairly minimal. So, if you run this code in your JavaScript console, and you have appended a query string to the page URL, you should see the object we created in the console.

Example # 2

In Example # 2, we expanded out the code with comments to make it easier to follow along. I won’t replicate each comment, but from a high-level perspective, here are the steps we take:

  1. Declare our variables at the top of the function (just good form)
  2. Get a reference to the query string, and chop off the question mark (i.e. omit “?”)
  3. Turn the query string into an array, using “&” as a delimiter
  4. Take that array, and split each element into a sub-array, using “=” as a delimiter
  5. That sub-array will always be a two-element array because on the left of the “=” is a key, and on the right side of it is a value
  6. Turn those two sub-array elements into a new “property / value” pair for our return object
  7. Repeat the last two steps for each sub array that was generated, by splitting the first array at “&”
  8. Now return our new object

Example # 3

In Example # 3, we added functionality that allows us to inject the values of our new object into the DOM. We use a for-in loop to iterate over the properties of our object. For each iteration of that loop, we inject a new LI element, with the appropriate markup for presentation. Note how we are using the variable “prop” and we also make a reference to “queryObject[prop]” which holds the value of the current property over which we are iterating.

Example # 4

In Example # 4, we have the full source code for our completed working example.

Here is the link to our full working example: http://examples.kevinchisholm.com/javascript/query-string/to-object/?fname=alfred&lname=newman&acctNum=010203&salesRegion=EastCoast&company=MadMagazine

Summary

In this article, we took at look at one way in which you can turn the query string into a JavaScript object. We learned how to get a reference to the query string, omit the question mark, turn the key/value pairs into an array, and then work with each element of that array to turn them into properties of our new object. We also learned how to inspect our new object and inject it into the DOM as markup.

Helpful Links for working with the Query String using JavaScript

http://en.wikipedia.org/wiki/Query_string
http://joncom.be/code/javascript-querystring-values/
http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
http://stackoverflow.com/questions/647259/javascript-query-string

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