JavaScript animation with jQuery.animate() – Introduction

jQuery

jQuery Logo
“How can I animate web page elements with JavaScript, using jQuery”?

Animation in JavaScript can be tricky. What at first may seem easy, quickly becomes a scattered mess of timeouts and callbacks. But with jQuery.animate(), you have a simple and elegant way of implementing animation in your web page, without all the headaches and jerky performance.

jQuery.animate() has a very simple syntax: Chain the return value of a jQuery collection with the .animate() method, pass in an options object, a speed value, and off you go. It really is that simple.

Before we get into the examples, here is the markup we will use:

Example # 1

Here is the jsFiddle.net Link for Example # 1: http://jsfiddle.net/jPaHy/

In Example # 1, we use a jQuery selector to return a collection. In this case, the collection contains only one element. Here’s a rundown of the syntax:

  • The jQuery selector “$(“.moveMe”)” returns a collection of one element
  • We chain-in the .animate() method to that return value
  • We pass-in an object to the .animate() method as the first argument
  • In that object, we have one property: “left”, and the value is: “+=500px”
  • The second argument that we pass in is the speed, which in this case is 4000 miliseconds (i.e. 4 seconds)

And that’s it!

Example # 2

Here is the jsFiddle.net Link for Example # 2: http://jsfiddle.net/BRWDr/

In Example # 2, we add a second chained .animate() method. There is little difference in the second call; instead of manipulating the “left” property, we manipulate the “top” property, which pushes the text down by 200 pixels.

Example # 3 – Using the jQuery.animate() callback function

Here is the jsFiddle.net link for Example # 3: http://jsfiddle.net/8FZ87/

In Example # 3, we pass-in a third argument. This, of course, is the callback function. What this means is that when jQuery.animate() finishes with the animation, it runs the callback function, if one is passed-in. You could certainly pass-in a named function, or as we have done, you can pass-in an anonymous function. In the callback, we change the color of the text to red, and change the text in the element to “all done!”.

Summary

The amount of JavaScript we would have had to write to accomplish this would have been a total pain in the neck. All that code is in jQuery, and it abstracts away the details, leaving you with a syntax that is both simple and elegant.

Once you have mastered the simple syntax of jQuery.animate(), moving elements around the page becomes trivial

Notice that in the markup, I applied the following CSS to the element that we want to animate: “position: relative;” We needed this because our examples manipulated the “left” and “top” properties. So, if the element was not positioned, nothing would happen when the JavaScript code ran.

The jQuery.animate() method makes it trivial to animate elements in a web page. Once you learn the syntax, it is incredibly easy. Of course, there is much more that can be done, and some impressive advanced features are available. This tutorial was meant only to explain the absolute basics of jQuery.animate(), so that if you have never used it before, you can get started right away.

Helpful Links for the jQuery.animate() method

http://api.jquery.com/animate/

http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation

http://viralpatel.net/blogs/understanding-jquery-animate-function/

http://james.padolsey.com/javascript/fun-with-jquerys-animate/

http://james.padolsey.com/demos/jquery/easing/

How to Create a JavaScript Object Literal

JavaScript

JavaScript LogoLearn how to quickly and easily create your first Object Literal, and give it properties and methods

There seems to be a bit of mystery surrounding the subject of JavaScript Object Literals. It is actually a simple concept and it’s easy to get started. There is a great deal of depth to the subject, but creating your first JavaScript Object Literal does not need to be complicated.

The simplest way to create an object literal is to assign an empty object to a variable. For example: var foo = {}; That is it. In that one line, you have created an object literal.

Now, that object is empty. Objects have two kinds of “things”: properties and methods. A property can be any valid JavaScript type (i.e. string, number, boolean, function, array, etc.). A method is essentially a property of the object to which you have assigned an anonymous function. So the property is now equal to a function. It is still a property of the object, but because it “does” something, we now call it a “method”.

Example # 1

Here is the JSFiddle Link for Example # 1: http://jsfiddle.net/jzrDw/

In Example # 1, we create a new Object Literal by assigning an empty object to the variable “foo”. Next, we give foo a property named “drink” and assign a value of “beer” to it. In this case the value of “drink” is a string (“beer”), but it could easily have been a number (i.e. foo.drink = 5) or a boolean (foo.drink = true) or any valid JavaScript type.

Example # 2

In Example # 2, we have added a second property to foo. This property, “say” has an anonymous function assigned to it, so now we call it a “method”. That method: foo.say does not do too much; it just outputs “hello world!” to the console. But nonetheless, it is a method of foo.

Here is the JSFiddle Link for Example # 2: http://jsfiddle.net/PWHM5/

Here is an important note: In the first two examples, technically, we created an object literal by assigning an empty object to the variable “foo”. Then we added a property and a method using dot notation (i.e. foo.property = value). But true “Object Literal” syntax involves creating the object properties as you create the object.

Example # 3

In Example # 3, we use Object Literal Notation. In the end, we have the same result as the previous example, but we achieve it using true Object Literal Notation. The difference is that in the previous example, we created an empty object, and then added properties to it. In Example # 3, we created those properties as we created the object itself.

Here is the JSFiddle Link for Example # 3: http://jsfiddle.net/sGY7E/

Summary

There is plenty more to talk about here. For example, there is the subject of “context” in Object Literals. But this post is about getting started, and to show that creating a JavaScript Object Literal is no mystery. What you do with that object is up to you. But you can be sure that objects in JavaScript are important features of the language, as they allow you to write more powerful and expressive code.

A Video Tutorial About JavaScript Object Literals

Helpful Links for JavaScript Object Literals

https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects

http://blog.kevinchisholm.com/javascript/difference-between-object-literal-and-instance-object/

http://www.dyn-web.com/tutorials/obj_lit.php

JavaScript Closures – The Absolute Basics

JavaScript

JavaScript LogoDemystifying this topic is one of the most important steps towards truly understanding the JavaScript language

It is a little difficult to get your head around JavaScript closures without a basic understanding of scope. I will not attempt to tackle that subject in any kind of detail here. But let’s at least consider this thought: JavaScript functions always (always) retain a reference to any variables that are in-scope when they are defined.

I know that sounds a little nerdy, but it is important to remember. if you are not quite sure what that means, take a little time to explore the concept of scope in JavaScript, then come back to revisit the topic of closures.

Assuming you are comfortable with the concept of scope, think about a function that is defined in the global scope. There is not much going on there because the global scope is the outer-most scope. But what about when a function is defined inside another function? That is where the power of closures starts to take place. When a function is defined within another function, it has access to any variables that are in-scope at the time of definition.

Example # 1

var foo = function(){ var drink = “beer”; return function(){ return drink; }; }; var bar = foo(); console.log( drink ); //wine console.log( bar() ); //beer

 

Here is the JsFiddle link: http://jsfiddle.net/Xt8HP/

In example # 1, we first create a global variable named “drink” and set it equal to “wine”. Next we have a function “foo”, that returns another function. When we say: ‘var bar = foo()’, we are assigning the value that foo returns to bar.

JavaScript functions always (always) retain a reference to any variables that are in-scope when they are defined.

Since foo returns a function, then bar is now a function. Because the function that has been assigned to bar is defined inside of foo, it has access to foo. This means that in our case, bar returns a private variable that lives inside of foo. That variable inside of foo named “drink”, has been set to “beer”. So, in the global context, “drink” equals “wine” and in the context of foo, “drink” equals “beer”.

The end result is that when we pass the variable “drink” to the console, it is “wine”, because in the global scope, “drink” is equal to “wine”. But when we pass “bar()” to the console, we get “beer”. That is because “bar()” is a function, it returns a variable named “drink” and because “Bar()” was defined inside of foo, it returns the first “drink” it finds, which is private to “foo()” and it is equal to “beer”.

At the most basic level, this is how closures work.

Summary

There is much more to talk about with regards to JavaScript closures. But for those of you scratching your heads, just trying to get the basics down, I hope this was helpful.

A video tutorial about JavaScript Closures

Helpful links for getting started with JavaScript Closures

http://www.zimbio.com/Computer+programming/articles/387/Javascript+Closures+basic+explanation

http://jpmcgarrity.com/blog/2011/03/basic-javascript-closure/

http://www.javascriptkit.com/javatutors/closures.shtml

How to Create a CSS Cache Buster Using JavaScript

JavaScript

JavaScript LogoUse the Date() constructor to create a unique query string; ensure each GET request is not cached

The other day, I was working with a customer whose iPad app was consuming an HTML page.
I was making changes to the CSS, yet was not seeing them in the iPad app. I kept adding a new query string to the URL of the CSS file, which forced the iPad app to download the updated CSS file. So, growing a little tired of changing the URL to the CSS element, I wrote a little cache buster script, and that was the end of the fiddling around.

This is very easy to do, so let’s look at an example.

Example # 1

In this example, we instantiate the Date() constructor, and get a reference to the time. Since this number is incremented by one, it will always be unique. We then create a new element, and set the required attributes: “rel”, “type” and “href”. The href has a query string that includes a reference to the time, so we have a GET request that is essentially different from the last one we made, and the next one we make will be different from this one, and so on.

Run this in your JavaScript console, and as long as you have a file name “style.css” in the same directory as your HTML file, you will see a new element appended to the <head> element. You can, of course, take the same approach with any resource that requires a web address such as a JavaScript file, an image, and so on.

Summary
Cache busting can ensure that often-changing files such as CSS and JavaScript always get downloaded by the client’s browser (i.e. never cached). It’s just a simple technique, but it can keep you from pulling your hair out.

Helpful Links for the subjet of cache busting

http://html5boilerplate.com/docs/Version-Control-with-Cachebusting/

http://www.adopsinsider.com/ad-ops-basics/what-is-a-cache-buster-and-how-does-it-work/

http://twosixcode.com/notes/view/simple-cache-busting-for-css-and-js

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

How to Use the jQuery replaceWith Method

jQuery

JavaScript LogoThe replaceWith() method provides a way to completely remove an element and put another in its place

Most of the time, jQuery is used to add click event handlers to DOM elements, and there’s nothing wrong with this. In fact, jQuery is so helpful in this context, it’s hard to argue against using it for your event handling / delegation. But just be aware… there are other tasks that come up, and some of them can get rather messy. One example is replacing one DOM element with another. Now this may sound simple, but with vanilla JavaScript, this kind of work can get pretty tedious. Normally, I recommend learning how to do things with vanilla JavaScript that you would want to do with jQuery, but there are times when this kind of wheel reinvention becomes a bad idea.

So, this is where the jQuery replaceWith() method comes in; it allows you to chop out one piece of the page and replace it with another. You simply specify the original section of the DOM as well as the new chunk, and then jQuery takes care of all the work. And what makes this method so helpful is the expressive syntax; on a high-level, it’s a simple as A.replaceWith(B). You really do have to thank the folks from jQuery, for packing a great deal of abstraction into this one method. If you don’t believe me, go ahead and try this yourself using just vanilla JavaScript. I think you’ll find that it’s pretty tedious.

Example # 1

In example # 1, we have attached an event handler to the element with the id: “foo”. When clicked, that element is removed from the page, and replaced with a piece of markup defined in a string. Yes, it’s that easy, and there are certainly more interesting things you can do with this jQuery method.

Summary

Replacing one section of the page with another piece of markup is quite easy with the jQuery replaceWith() method. The syntax is very straight-forward and if you are already familiar with jQuery, there are quite a few possibilities.

Helpful links for the jQuery replaceWith method

http://api.jquery.com/replaceWith/

http://www.w3schools.com/jquery/html_replacewith.asp

http://stackoverflow.com/questions/730916/whats-the-difference-between-jquerys-replacewith-and-html

http://stackoverflow.com/questions/5248721/jquery-replacewith-fade-animate

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

The JavaScript for…in statement – enumerating object properties

JavaScript

The JavaScript “for in” statement allows you to literally “loop” through all the properties of an object, without knowing ahead of time what the object will be or how many properties it will have

Seems as though one of the most over-looked and under-used tools in the JavaScript language is the “for in” statement. This statement allows you to essentially say: “Hey, if I have an object, any object, I wanna know what the name and value of every one of it’s properties is.”

No problem dude.

The “for in” statement creates a loop, much like the typical “for ( i=0, i <+ ###, i++)”, but  you can think of it as more of: “for (x = the first property in an object, go until x == the last property in the object, go to the next property in the object”). Needing to know all the names and values of a given object at run time is a scenario that comes up more than you may think, and being able to satisfy that need is a huge (huge) asset.

Example # 1

So, in Example # 1, we created a JavaScript object literal and assigned it to the variable “car”. This object has four properties. We then use a JavaScript “for in” loop to literally loop through the properties of this object. note that in order to build our dynamic statement, we first reference “prop”, which is the variable that represents the name of the currently examined property (i.e. “maker”). In order to the actual value of prop, we use bracket syntax, as opposed to dot notation or dot syntax. This is because in order to use dot notation, we would have to actually know the name of the property (i.e. “car.maker”). Since we only have a variable to use, we can say “car[prop]”, because bracket notation allows us to use a variable, or any valid JavaScript expression inside the bracket.

The output of example # 1 would be:

The maker of this car is: honda
The color of this car is: blue
The type of this car is: sedan
The mpg of this car is: 32

Summary

So, as you can see, the JavaScript “for…in” statement is easy to use and incredibly useful. It helps to write code that deals with objects that are unknown at run time, but as a result, can be easily enumerated and acted upon.

Helpful links for the JavaScript “for in” statement

http://store.kevinchisholm.com/javascript-training/javascript-object-inspection-using-the-for-in-statement/

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

http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/

http://webreflection.blogspot.com/2009/10/javascript-for-in-madness.html

How to use the JavaScript indexOf() method to find the position of one string in another string

JavaScript

JavaScript LogoThe JavaScript indexOf() method allows you to find out if a string contains one or more characters, and if so, the starting position of that set of characters

If you’ve ever found yourself saying: “How do I figure out if one string contains a certain character or a sub-string?” then the JavaScript indexOf() method is for you. It returns the starting position of a string, even if it is one character. If that string does not exist, then it returns “-1”. So, if you want to know if a given string even exists at all in another string, simply test to see whether or not the JavaScript method indexOf() returns “-1”. If it does, then the sub-string does not exist. If the return value is “> -1” (i.e. more than -1), then the string does exist.

Example # 1

In Example # 1, we check for the starting position of “football” within the string “Hello world”. Because “football” does not exist in “Hello world”, the return value is “-1”

Example # 2

In Example # 2, we use an “if else” condition to test for the string “football” in “hello world”. In this case, it does not exist.

Example # 3

In Example # 3, we have included the string “football” in “hello world”, so the test returns the starting value of “football”, which is “6”. So, the test evaluates to “true”, the “true” text is displayed, and at the end of that text, we return the starting position of “football”.

Summary

The JavaScript indexOf() method is the best way to find out if one string exists inside of another. If it does, the starting position of that searched string is returned. If the sub-string does not exist, then “-1” is returned; this is  a reliable indicator of “does not exist”.

Helpful links for the JavaScript indexOf() method

http://www.w3schools.com/jsref/jsref_indexof.asp

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

http://www.tizag.com/javascriptT/javascript-string-indexOf.php

 

JavaScript Interview Questions: Object-Oriented JavaScript

Object-Oriented JavaScript

QUESTION:

True or False: the terms “scope” and “context” refer to the same thing in JavaScript.

Click for Answer

QUESTION:

If you omit the “var” keyword when creating a variable in a function, it becomes a property of what object?

Click for Answer

QUESTION:

How do you determine if a JavaScript instance object was created from a specific constructor or not?

Click for Answer

QUESTION:

True or False: Once you create an object, you can add, remove or change properties of that object at any time.

Click for Answer

QUESTION:

True or False: You can only instantiate a JavaScript constructor function once.

Click for Answer

QUESTION:

When you create a function inside of a method, what does the “this” keyword refer to when used in that function?

Click for Answer

QUESTION:

Name two ways two change the context of a JavaScript method

Click for Answer

QUESTION:

Can a JavaScript constructor return a primitive value (e.g. a number or a string)?

Click for Answer

QUESTION:

In JavaScript, are objects passed by reference or by value?

Click for Answer

QUESTION:

What is the difference between a constructor function and a non-constructor function with respect to the word “this”

Click for Answer

QUESTION:

What is the name of the property that allows you to add properties and methods to an object, as well as every object that inherits from it?

Click for Answer

QUESTION:

True or False: An object literal can be used to create private variables.

Click for Answer

QUESTION:

What is the name of the object that refers to the application used to view a web page?

Click for Answer

QUESTION:

True or False: The object returned by the document.getElementsByTagName() method is an array.

Click for Answer


QUESTION:

Which object.property combination provides a reference to the protocol used to view the current web page?

Click for Answer

QUESTION:

Given the below code, what line of JavaScript would allow foo.getColor to return the value of foo.color, without using the word “foo”?

Click for Answer (+)

QUESTION:

What is the difference between using dot notation and bracket notation when accessing an object’s property?

Click for Answer (+)

QUESTION:

What is important to remember about the last property’s value in a JavaScript object literal?

Click for Answer

QUESTION:

Given the following code, what is very likely the reason that the programmer made the first letter of “Foo” a capital letter?

Click for Answer

QUESTION:

Given the following code, how would you instantiate the function “Foo” and assign it to the variable “bar”?

Click for Answer

QUESTION:

What are two ways in which the variable “foo” can be assigned to an empty object?

Click for Answer

QUESTION:

True or False: When you create an object literal, you must first instantiate the Object() constructor.

Click for Answer

QUESTION:

When using the addEventListener() method to create a click-handler for a DOM element, what is the value of “this” inside of the callback you specify?.

Click for Answer

QUESTION:

True or False: A JavaScript array is not an object

Click for Answer

QUESTION:

If a string is a primitive value, why does it have a split() method?

Click for Answer

QUESTION:

True or False: A function can have its own properties and methods.

Click for Answer

Two Alternatives to the jQuery Document Ready Function for JavaScript

jQuery

jQuery Logo

There are two alternatives to document ready that are a bit easier to type

Most JavaScript programmers are familiar with jQuery’s document ready function. There is no doubt that it is a very helpful way to wrap your JavaScript with a cross-browser compatible function that will not run until the document has achieved a “ready” state. While the syntax is fairly simple, there are two slightly less verbose alternatives to the exact same functionality.

Example # 1

 

In Example # 1, we have the standard syntax for the jQuery document ready function.

Example # 2

 

In Example # 2, we omit the “document / ready” portion of the equation, and simply insert our function in the following expression $().

Example # 3

In Example # 3, we chain a jQuery ready() function to the return value of the jQuery object: $().ready(). So, when the jQuery object is ready, so is our code.

Summary

There is no doubt that the jQuery document .ready() function is super-useful. There is however, more than one way to invoke this functionality.

Helpful links for the jQuery document .ready() function

http://api.jquery.com/ready/

http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

http://rpheath.com/posts/403-jquery-shorthand-for-document-ready

http://think2loud.com/653-jquery-document-ready-howto/

 

 

 

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

What is the difference between an Object Literal and an Instance Object in JavaScript ?

JavaScript

JavaScript LogoAlthough a JavaScript object literal and a JavaScript instance object are both objects, they differ in their inherent nature and features


Object Literals

An object literal is “flat”. You create it, you add properties and methods to it, and all of those properties and methods are public. You can mutate any members of that object at any time. A JavaScript object literal does not, by nature, provide private scope. But any of the members of an object literal can certainly be a function that is capable of private scope. Object literals are useful because they allow you to create clean name-spaced code that is easy to pass around and consume.

Example # 1

In example # 1, we have defined a JavaScript object literal and assigned it to the variable “data”. This object has two members: the property “fname” and the method “addOne”. At run time, we can mutate this object very easily and add new properties (e.g. “lname”) and methods (i.e. “say”). The upside is that this object is totally exposed and we can access or mutate any of its members any time we like, with no problem. (Remember that if an object member is a function, then that function does provide its own private scope.) The downside of this object is that it does not inherently have a private scope. It also doesn’t have the kind of initialization that is provided by a constructor upon creation.

The output for example # 1 is:

foo
5
bar
baz
this is the say function

Instance Objects

An instance object is what is returned when instantiating a JavaScript constructor function, using the JavaScript “new” keyword. When you say “var bar = new Foo()”, “bar” becomes an “instance” of the function “Foo()”. Any expressions within Foo() are executed, any local variables in Foo() are copied and provided in “bar”, and the value of “this” inside of “bar”, refers to “bar”. The function “Foo” is never changed in any way; it simply acts as a “blueprint” for “bar”, and “bar” is an “instance” of “Foo”. Any local variables inside of “bar” are completely private and can only be muted by privileged members of that object.

Example # 2

In example # 2, we have created a constructor function. A JavaScript constructor function is a function that is not meant to be executed directly. For example, we never plan to do the following: “Foo()”. Instead, a constructor is meant to be instantiated. This means that you create an “instance” of that function using the JavaScript “new” keyword. We have created an instance of Foo() by saying “var bar = new Foo()”. So, now we have a variable named “bar” that is an exact copy of Foo().

What makes “bar” differ from our JavaScript Object Literal that we defined in Example # 1, is that when our instance object (“bar”) is created, any execution code in the constructor (i.e. “Foo()” ) runs. In addition, any private variables defined in the constructor remain private in the instance object (i.e. “_color”).

What makes this scenario a little more special than that of the object literal is that we can have privileged methods. These are methods that are made public by the use of the “this” prefix, but they have access to the instance object’s private members (i.e. “_color”). So, when we run this code, the constructor function code runs (“welcome to your new instance object”). We attempt to output the value of “_color”, but “undefined” is returned, because “_color” is private and cannot be accessed outside of “bar”. We then use the privileged method “getColor()” to get the value of _color the correct way, and “blue” is returned. We then change the value of “_color” using the privileged memer “setColor()”, and return its value using “getColor()” again (“red”).

Summary

Both Object Literals and Instance Objects have their place and purpose in JavaScript. The power of Object Literals is in their lightweight syntax, ease of use, and the facility with which they allow you to create name-spaced code. Instance Objects are powerful because they are derived from a function, they provide private scope when they are created, and expressions can be executed on instantiation.

Helpful links for JavaScript Objects

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

http://www.javascriptkit.com/javatutors/oopjs.shtml

http://www.dyn-web.com/tutorials/obj_lit.php

http://www.davidpirek.com/blog.aspx?n=JavaScript-Class-Constructor-vs.-Object-Literal:-Difference-in-Implementation-and-Inheritance

Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

JavaScript

JavaScript LogoKeeping the global namespace clean is a good idea. Immediate functions allow the JavaScript programmer to do so with a great deal of power.

In a previous post, we discussed the topic of the JavaScript Immediate Function. Now let’s re-visit this topic with a focus on creating a private scope with which we can interact.

Most JavaScript programmers know that you can create an object, and then extend that object by simply assigning a new property to it. In fact, you can even do so at run time. Well, this is all very nice, but as you do so, these new properties are public. Which means, of course, that they are accessible to anyone and mutable at any time. So, while this can have it’s uses, there is a downside, because any line of code has access to these properties and can change them. Sometimes, that can get messy.

Example # 1

In Example # 1, we created a global variable named “foo”. We then added two properties to it: “name” and “say”. There is no reason why at a later point in our code, we couldn’t intentionally (or even worse, accidentally) do the following:  foo.name = “marge”. If this is intentional, no problem, but if it is done by accident, it creates cases that become frustrating to debug and manage. So, obviously, what we need is a way to store values inside of foo that have a clearly defined interface for retrieval and mutation.

Example # 2

{ var _name = “bart”; var MyConstructor = function(){ this.getName = function(){ return _name; }; this.setName = function(newName){ _name = newName; }; } return new MyConstructor(); })(); console.log( foo.getName() ); console.log( foo.setName( “simpson” ) ); console.log( foo.getName() );

In Example # 2, we have drastically altered our global variable so that it is an immediate function. Inside of that immediate function, we have a private variable called “_name”. We return an instance of our constructor function, which allows us to use the “this” keyword to create privileged members. These two functions allow us to set, and get the value of name. If you paste Example # 2 in your JavaScript console, and run it, you will see that the value of our private variable “_name” changes over the course of the two “get” statements. This is because in between these two get statements, we use the “setName” method to change the value of that private variable.

Summary

The JavaScript immediate function can be used to create a global variable that has its own private scope. This is useful when creating functionality that requires storing data for the life of the page and managing access to that data.

Helpful links for Immediate Functions in JavaScript

http://dreaminginjavascript.wordpress.com/2008/07/03/immediate-execution/

http://lostechies.com/derickbailey/2011/12/04/achieving-block-scope-with-immediate-functions-in-javascript/

http://www.jameswiseman.com/blog/2011/02/17/jslint-messages-wrap-an-immediate-function-invocation-in-parentheses/

http://www.jspatterns.com/self-executing-functions/

 

 

Understanding the difference between null and undefined in JavaScript

JavaScript

JavaScript LogoIt is quite common to confuse null and undefined, but there is an important difference between them.

null

Simply put, null is a JavaScript keyword that indicates the absence of a value. Surprisingly, if you run the following in your firebug console:  console.log( typeof null ), you will see “object”. Don’t be fooled though. This object is not mutable, has no properties, and there is at all times only one instance of it. It simply evaluates to “no value”. Although, this is a perfectly valid value in JavaScript. If you want to strip a variable of any value, assign it to “null”.

Example # 1

In Example # 1,  we created an object called “foo”. The console.log statements demonstrate the odd, yet perfectly valid behavior of “null”. At first, the type of foo is “object”. After we assign foo to null, it is still an “object” type, yet when we console.log the value of foo, it is simply “null”.

undefined

In JavaScript, “undefined” is a global variable (a property of the global object), that is created at run time. This global variable represents something  that has not been initialized. It also represents an object property or array index that does not exist. Also, when you do not supply an argument for a function parameter, it will have the value of “undefined”. Furthermore, when a function does not return a value, it returns “undefined”. Have you ever wondered why sometimes when you execute a function in the FireBug console, you see “undefined” in the console? That is because while your function may actually do something wonderful, if it does not explicitly return a value, then it returns “undefined”.

Example # 2

In Example # 2, when we attempt to determine what type “undefined” is, we are told that it is of the type “undefined”.  Hence, there is only one instance of the “undefined” value, and it has the value of “undefined” (do you have a headache yet?). In the second line, we attempt to output the value of foo to the console, but we get a “ReferenceError”. This is because while asking what the type of an undeclared variable is does not harm anyone (it is the type “undefined”), attempting to access that variable causes an error because it essentially does not exist. But, if we assigned foo to “null”, and then tried to access it, no problem. This is because if we assign foo to “null”, it has a value, and that value is “null” (i.e. “no value”). But when something evaluates to “undefined”, it does not exist.

Summary

In JavaScript, “null” and “undefined” have different meanings. While “null” is a special keyword that indicates an absence of value, “undefined” means “it does not exist”.

Helpful links for JavaScript “null” and “undefined”

http://saladwithsteve.com/2008/02/javascript-undefined-vs-null.html

http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-_2F00_-EcmaScript.aspx

http://sharkysoft.com/tutorials/jsa/content/045.html

 

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

 

 

Building Dynamic HTML Markup with JavaScript – the Basics

JavaScript

JavaScript LogoWhen you need to iterate over a data set, and build markup using its elements, there are a few techniques that make this a snap

Sometimes you may need to build markup and insert it into the page, but perhaps you do not know what that markup will be. Actually, you would probably know most of what will happen: you have some markup that needs to be repeated one or more times, and in each iteration, the text in certain elements will change. A typical scenario is one in which you have multiple records in a data set, and you need to create a series of elements that will be similar, but each row in the data set will have it’s own copy of the markup and display its values. Same markup, but unique values with each iteration.

Example # 1

 

In Example # 1, we first created our data set (the variable “arr”), which is a JavaScript array. Each element of the array is an object literal, containing three fields. We then proceed to loop through all the elements of the array and for each one, we create a form. In each form, we mix the markup (which is the same with each iteration), but mix in the values from the data set so that when finished, each element in our data set has its own HTML form (think of it as rows in a table or records in a database). When we are finished creating the markup, we simply use the jQuery .html() method to insert our markup into the DOM, using the ID of a specific HTML element.

Two Quick Notes:

Variable Declarations – When declaring multiple variables, keep in mind that you can do so with one “var” statement, and separate each variable name with a comma. This makes things a bit easier to read and some argue that it is faster.

String Concatenation – Instead of one insanely long string, you can use the “+” operator, and break your assignments into multiple lines. Although this is JavaScript, it makes it look a bit more like actual markup.

Summary

There are, of course, much more elegant ways to do this; John Resig’s JavaScript Micro-Templating technique is a cool example. And there are plenty of others out there.  Here, I’ve simply covered the basic concept of working with data, and creating HTML on the fly to present that data in the page, regardless of the amount of data, or values it contains.

Helpful links for building dynamic HTML markup with JavaScript

http://markalexanderbain.suite101.com/an-introduction-to-dynamic-html-with-javascript-a74777

http://www.scriptingmaster.com/javascript/outputting-dynamic-HTML.asp

http://stackoverflow.com/questions/6106402/php-vs-javascript-for-dynamic-html-pages

Super Easy HTML Video Support with LongTail Video’s JW Player and JavaScript

JavaScript

JavaScript LogoThis video player makes it simple to present video in your HTML page, and configure a wide array of options

While the new HTML5 video element brings much promise to the concept of full native browser support, it can still be a bit of an effort to provide cross-browser consistency. LongTail Video’s JW Player offers a way to implement some fall-back support and very cool customization. This little puppy does a great job of auto-detecting which method of playback is supported by the user’s device, and presents accordingly. There is support for both Flash and HTML5, skinning, plugins and a very robust API. At the bottom of this post are a few links that will more than get you started. I’ll simply highlight how easy it is to get JW Player up-and-running in your web page.

Example # 1

In example # 1, just to demonstrate that the most current version of JW Player works with a two-year-old version of jQuery, we pull in jQuery 1.4, and what would be a local copy of the jwplayer.js. With that done, we simply call the jwplayer() method, passing in the ID of the element within which we’d like the video player to run, and chain the return value to the JW Player .setup() method. We pass a configuration object to that method, and away we go! The only two requirements here are the jwplayer.js file and the player.swf file.

Example # 2

In example # 2, we added an “events” property to the configuration object, and to that property, we added an onReady method, which starts the video once the player is ready.

Example # 3

In example # 3 there is a code snippet that demonstrates the ability to remove a video from the page. JW Player takes care of all the DOM cleanup, including removing any bound events. You can add the video back in real-time by simply running the original function that appeared in the document.ready() method.

Summary

There is plenty (and I do mean plenty) to sink your teeth into here. I’ve only scratched the surface of the surface. If you are looking for a plugin that makes video support easy and offers tons of options, JW Player is a serious contender. Non-commercial use requires no payment and the commercial licence is very reasonable.

Helpful links forJW Player

http://www.longtailvideo.com/players/

http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/12540/javascript-api-reference

http://wordpress.org/extend/plugins/jw-player-plugin-for-wordpress/

jQuery Under the Hood with Paul Irish

jQuery

jQuery Logo

If you’ve never poked around inside of jQuery, you should. Paul’s videos are a great way to get started

I decided to ring in the new year with two of Paul Irish’s videos that I had book-marked, but had not gotten around to viewing: 10 Things I Learned from the jQuery Source and 11 More Things I Learned from the jQuery Source.

In these two videos, you have Paul’s screen, so that you can follow his code, and a small sub-screen of his head while he talks, so that you can follow his hilarious commentary and thought pattern. My only complaint: there is so much good stuff here to dive into that it takes an hour to watch a 30 minute video because of the constant temptation to hit “pause” and then fire up JSFiddle and play around with the concepts that he discusses.

10 Things I Learned from the jQuery Source – YouTube

In general, exploring the un-minified version of jQuery is just plain ol’ good sense. There is a tendency to simply use jQuery and treat it as some magic black box that “just works, and works great…” But the fact of the matter is, there is only one thing going on inside of that giant self-executing function: JavaScript. That is it.

Everything that jQuery does for you, you could have done for yourself… but, jQuery is better, stronger and faster than the average bear. Fair enough. But, that does not mean that we should not lift up the hood, poke around and learn from the code inside… because what is going on in there is pretty dammed cool. The jQuery folks do things in some very interesting ways and there are tons (and I do mean tons) of neat stuff to learn from.

11 More Things I Learned from the jQuery Source – YouTube

Highlights of Paul’s videos include a brief discussion of jQuery’s “no conflict” feature,  his decision to hijack the .ready() method, and a hilarious discussion of how jQuery detects the presence of Internet Explorer (and the technique used is just so brilliantly creative that I had to once again pause the video, copy the code while squinting at the YouTube page, and try it in notepad myself… it just works).

If you are a JavaScript developer, you owe it to yourself to check out these videos. Paul Irish is pretty funny, and he is one of the top web developers out there. This combination makes all of his videos a pleasure to watch (and most importantly, to learn from).

Writing Argument-Agnostic JavaScript Functions

JavaScript

JavaScript LogoThere is no need to tightly couple a function and the other function that might call it, by sweating the details of the arguments passed in. You can access the local “arguments” variable, examine it, and decide how to handle the situation

Somewhere, I still have the code from my first fairly serious JavaScript project. From time to time, I like to take it out and look it over. It’s riddled with functions that, while written in good spirit, clearly reveal my level of inexperience at the time. This is not something I am proud to discuss publicly, but it is the truth. And, I always tell myself that everything is relative; some day I will look back on code I wrote last week and recoil with the same horror. Programming is a never-ending learning process and while the initial learning curve is steep, the process never ends; we always strive to improve our skill set.

One of the things that really stood out in my mind was how many functions I wrote that looked something like this:

While I don’t think it’s completely insane that I would write a function that takes so many specific arguments, I’ve come to realize that this approach tightly couples the function with the other function that might call it. The reason I keep mentioning “…might” is that in many cases, we write functions that are probably called in the lifetime of the program, but as many JavaScript apps are event-driven, it is not unusual for events to sometimes not happen, which means that functions are sometimes not called.

The point here is that tightly-coupled functions are, of course, sometimes unavoidable, but to me, it always seems a shame to have to write a function that is tightly coupled to its caller, but may never be called. So, I started to think about decoupling these functions from each other as much as possible. Granted, a function like “updateRecord()” will likely only be called to… well… update a record, but we can make it a bit more generic so that we don’t have to worry so much about what arguments were passed in when we write our code. We can simply write the function as if all the arguments we need have been passed in, and then “handle” the corner cases where some arguments are missing. This also frees up the caller in that there is reduced stress, as well, from that end; the caller can pass-in all the expected arguments, some of them, or none of them. What happens in these cases is, of course, up to us, but it does not always have to be an “all or nothing” scenario.

 Example # 1

In Example # 1, we don’t assume any arguments are passed in. We first test to see if the local “arguments” variable has a length that is greater than 0. If it does, great; we can then do something with the arguments. Most likely, we will want to examine them and see if the ones we need are available.

It is important to note that the “arguments” variable is not a true JavaScript array. The subtle details of this are worthy of another post. But keep in mind, it is simply a local variable that is array-like, in that it is an indexed list that can be iterated over and it does have a “length” property.

 Example # 2

In Example # 2, we loop through all of the arguments. Inside the loop, we could examine each argument and see if it meets the needs of the function.

Example # 3

In Example # 3, we pass an object in as the argument to our “updateRecord()” function. What is helpful about this approach is that the “updateRecord()” function does not break or throw an un-handled exception if we pass in too many arguments, not enough arguments, or no arguments. The function simply covers the following:

  1. Were any arguments passed in?
  2. If more than zero arguments were passed in, let’s loop through each one
  3. On each loop, if the argument being examined is an object, let’s loop through its properties
  4. On each sub-loop, we can do something with each property

Granted, your function may be a bit useless unless the exact number of arguments are passed-in and they are named in some exact way. But, your function does not have to be completely useless. It can handle corner cases gracefully, return a useful error, or maybe even partially carry out its intended task. The assumption here is that you or someone on your team will write this function and the one that calls it, so in the end, you can implement your own logic to make this function useful, yet unbreakable.

Summary

This topic is more of a pattern than a specific implementation. I like to use it because I prefer to keep my functions as loosely coupled as possible. It may not always be possible to keep them 100% uncoupled, but I prefer a pattern in which I can pass a function the right, wrong, or partially right number of arguments, and that function can inspect what it gets and handle the situation gracefully. A big plus when passing in an object, is that you can at least not worry about the order of the arguments; you simply grab the passed-in object, and enumerate the properties. What you do with what you find is up to you.

Helpful links for the JavaScript arguments property

https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments

http://javascript.info/tutorial/arguments

 http://stackoverflow.com/questions/5303003/best-use-of-the-arguments-property-in-javascript