check whether an object exists

In javascript, how do I know whether a particular object exists or not?

For example, suppose f is a form,

var field = eval("f." + "address");
field.value = "USA";

This code is fine if there is a field named "address" in the form, but if such
a field does not exist (since the javascript function will be a common one)
how can I tell that field is undefined and therefore skip the assignment
which will cause an error?

Must work for IE and Netscape.

Who is Participating?
Michel PlungjanConnect With a Mentor IT ExpertCommented:
1. Test for undefined, null, blank, or zero:
if (field) ...

2. test for object:
if (typeof field == 'object') ...

2. Much better test and assignement for fom fields:

for (i=0;i<f.elements.length;i++) {
   if (f.elements[i].name == 'address') f.elements[i].value = 'USA';

fasterAuthor Commented:
The last option is actually not what I want, because it requires an iteration of all fields of the form, which is expensive.  The 1st is good for me.
Michel PlungjanIT ExpertCommented:

But how many fields do you have? It would take at least 50+ fields to make a difference as far as I have seen.

I was just having this problem myself, and I thought this may help:

//JavaScript 1.3 added the if(x==undefined) capability, but previous versions require a workaround
function isDefined(o) {
      varToStr=eval("' "+o+"'");
      if (varToStr==" undefined") {
            return false;
      } else {
            return true;
Michel PlungjanIT ExpertCommented:
And also added === that will test for null

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.