Welcome Guest
( Log In | Register )
The time is now 12:47 am
You last visited June 20, 2021, 10:58 pm
All times shown are
Eastern Time (GMT-5:00)

Snippet to enumerate JavaScript object properties


Last Edited: January 20, 2007, 4:37 pm

In writing some JavaScript code today, I had to write a function that was being called by some other JavaScript function, and I had no idea how many argument (parameters) were being sent by that other function, or what the contents of those argument would be. 

So, I figured out a nice way to determine what was being sent to my function.

First, determining the number of arguments being sent was pretty easy.  In every function, JavaScript automatically creates an array called arguments[].  So to find out how many arguments are being passed to my function, I created the following code:

function myFunction() {

Then, when I opened the web page and the JavaScript function was called, I saw a "2" displayed in an alert box, so 2 arguments were being passed.  That part was easy!

Next, I changed my function to display what type of arguments were being passed:

function myFunction() {
  alert(typeof arguments[0]);
  alert(typeof arguments[1]);

Then when the function executed I saw 2 alert boxes, each with the word "object".  So I knew I was being passed 2 objects as arguments.

The last step was to examine the 2 objects to see what was inside them.  To do that I came up with a way to enumerate the properties of each object.

In JavaScript objects are really nothing more than arrays that are stored in something called "JSON" (JavaScript Object Notation).  JSON represents objects as arrays of name/value pairs.  The name part is a string value and the value part is any valid JavaScript type, such as string, number, or function.

So enumerating the object properties was just a matter of using two for loops to read all the elements of the array.  The function became:

function myFunction(arg1, arg2) {
   var property, properties="";

   for(property in arg1){
      properties += (property + ": " + arg1[property] + "\n");


   for(property in arg2){
      properties += (property + ": " + arg2[property] + "\n");


Then when the function executed I saw two alert boxes, the first one showing full contents of the first argument, and the second alert box showing the contents of the second argument.

Now that I know the contents of the arguments, I can go on and finish my JavaScript function!

This is a nice little snippet to keep in reserve in case something like this happens again.

Entry #335


This Blog entry currently has no comments.

You must be a Lottery Post member to post comments to a Blog.

Register for a FREE membership, or if you're already a member please Log In.