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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Michel PlungjanIT 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';


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.