Can I check if an object exists?

R

Randell D.

Folks,

I have written some scripting tools that are compatable with alot of my
pages - For example, I've created a script that will check to ensure
certain form fields that require data, are completed. In order for this
to work, I must pass it the form name, and the field names (input tag
names).

Sometimes I copy/paste the syntax from one page to another and I might
forget to change the form name, or an input tag name passed in the
function call with the result that I get a message in the Mozilla js
console about an object with no properties.

Can I have my scripts test for this? Can I test, for example, if
document.forms[formName] exists, where formName is a variable? If so,
what would be the best method for me to test for this?

Thanks... replies via ng so that all can learn... is greatly appreciated,

randelld
 
Z

ZER0

Can I have my scripts test for this? Can I test, for example, if
document.forms[formName] exists, where formName is a variable? If so,
what would be the best method for me to test for this?

if (typeof document.forms[formName]!="undefined"){
/* do something */
}else{
/* is undefined */
}
 
R

RobG

ZER0 said:
Can I have my scripts test for this? Can I test, for example, if
document.forms[formName] exists, where formName is a variable? If so,
what would be the best method for me to test for this?


if (typeof document.forms[formName]!="undefined"){
/* do something */
}else{
/* is undefined */
}

Just to expand a little on Mike's reply, the above type test is
required if you are testing a function that may return zero
and therefore even though it is supported, it will fail the
test.

e.g. if (document.body.scrollLeft) {
...
}

Will return zero if the document hasn't actually been scrolled
to the right and the test will fail.

Even if you wanted to use this type of test on the forms
collection, I think:

if ( document.forms[formName] != 'undefined'){

would be sufficient.
 
Z

ZER0

if (typeof document.forms[formName]!="undefined"){
Just to expand a little on Mike's reply, the above type test is
required if you are testing a function that may return zero

typeof is simply more precise than "if (somevar)".
Even if you wanted to use this type of test on the forms
collection, I think:

if ( document.forms[formName] != 'undefined'){

Mhm. You try to check if document.forms has a property called as formName's
value, and the content is "undefined".

--
ZER0

~ The Tangent Universe collapsed 5965 days, 9 hours, 42 minutes and 2 seconds ago.

on air ~ "Utada Hikaru - Hikari - PlanitB Remix"
 
R

RobG

ZER0 wrote:
[...]
Even if you wanted to use this type of test on the forms
collection, I think:

if ( document.forms[formName] != 'undefined'){


Mhm. You try to check if document.forms has a property called as formName's
value, and the content is "undefined".

The above test will suit provided the user's browser supports
the forms collection. If a genuine "belt and braces" approach
is required, then a test for document.forms should be performed
first as if the typeof test fails, you don't know why - assuming
that 'why' is important to the OP.

The OP's need seems to be more for a debugging tool, not a
thorough test of some browsers' capability and on that basis,
document.forms is very likely to be supported.
 
M

Michael Winter

RobG wrote:

[snip]
if ( document.forms[formName] != 'undefined'){
[snip]

The above test will suit provided the user's browser supports
the forms collection.

True as no FORM element will have a toString value of 'undefined'.
However, both that and a typeof test require a string comparison which
should be slower than the boolean conversion of an object reference,
and I see no maintainance benefit to either of the more verbose
approaches.

[snip]

Mike
 
Z

ZER0

if ( document.forms[formName] != 'undefined'){
Mhm. You try to check if document.forms has a property called as formName's
value, and the content is "undefined".
The above test will suit provided the user's browser supports
the forms collection.

Sorry, my english is not very good.
I don't understood the reason of that comparison.

--
ZER0

~ The Tangent Universe collapsed 5965 days, 10 hours, 39 minutes and 19 seconds ago.

on air ~ "See Saw - Edge"
 
Z

ZER0

However, both that and a typeof test require a string comparison which
should be slower than the boolean conversion of an object reference,

Mhm, it seems no true.
You can see that if you make a simply benchmark.
and I see no maintainance benefit

It's simply: The typeof method is not so ambiguos like a boolean conversion
of an object reference.

But everyone has own coding style, of course.

--
ZER0

~ The Tangent Universe collapsed 5965 days, 10 hours, 42 minutes and 33 seconds ago.

on air ~ "See Saw - Edge"
 
M

Michael Winter

ZER0 wrote:

[RG:]
if ( document.forms[formName] != 'undefined'){

Sorry, my english is not very good.
I don't [understand] the reason [for] that comparison.

If you attempt to compare an object to a string

if(obj == 'string') {

(or a number for that matter), the object is converted to a
primitive[1]. If the object has a valueOf method, this will be called
and its return value will be used for the comparison:

if(obj.valueOf() == 'string') {

If a valueOf method doesn't exist, the same process will be attempted
with the toString method:

if(obj.toString() == 'string') {

As you probably know, elements have toString methods that return
values like '[object HTMLSelectElement]' and '[object
HTMLFormElement]'[2]. In addition, the value undefined will convert to
the string 'undefined'. Rob's suggestion will attempt to compare these
values and obviously, only an undefined property will convert to
'undefined'.

Hope that helps,
Mike


I suggest you read the ECMAScript specification (ECMA-262) with regard
to the abstract equality comparison algorithm (11.9.3), the internal
ToPrimitive operator (9.1), and the internal [[DefaultValue]] method
(8.6.2.6) for a complete description of the process. Mine was very
much specific to this case.

[1] A primitive is any one of undefined, null, boolean, number and string.
[2] IE doesn't follow the ECMAScript specification in this regard and
instead returns a generic value of '[object]' for all elements.
 
M

Michael Winter

Michael said:
[RG:]
if ( document.forms[formName] != 'undefined'){

For this statement to behave as desired, and for my previous
explanation to be correct, the former must be modified to provide
unconditional conversion-to-string for the object reference. That is:

if(String(document.forms[formName]) != 'undefined') {

Mike
 
M

Michael Winter

ZER0 wrote:

[Regarding the comparison]
Mhm, it seems no true. [...]

See the other sub-thread where I respond to myself. It can work if
it's modified slightly.

[MLW:]
I see no maintainance benefit
[snip]

But everyone has own coding style, of course.

Precisely. I think that most scripters are (and every scripter should
be) capable of reading

if(object.method) {

as "if 'method' exists as a member of 'object'". That's why I see no
benefit. In fact, I think the verbosity complicates the statement and
makes it more difficult to understand - at least at a glance (which is
how I tend to read code).

As Rob said previously, there are times when a typeof test is a must:
when a value could be a primative and you're testing for the existence
of a property. However, I think it's overkill when you're testing only
objects.

Mike
 
R

Randell D.

Randell said:
Folks,

I have written some scripting tools that are compatable with alot of my
pages - For example, I've created a script that will check to ensure
certain form fields that require data, are completed. In order for this
to work, I must pass it the form name, and the field names (input tag
names).

Sometimes I copy/paste the syntax from one page to another and I might
forget to change the form name, or an input tag name passed in the
function call with the result that I get a message in the Mozilla js
console about an object with no properties.

Can I have my scripts test for this? Can I test, for example, if
document.forms[formName] exists, where formName is a variable? If so,
what would be the best method for me to test for this?

Thanks... replies via ng so that all can learn... is greatly appreciated,

randelld

Gentle People...

Who would have thought the question would have brought on such a
discussion - however I am grateful to the response. I can understand
the arguements you guys were bouncing around as I have some previous
(non-Javascript) programming experience.

Much appreciated... thanks again,
randell d.
 
Z

ZER0

On Mon, 28 Feb 2005 17:14:36 GMT, Michael Winter wrote:

[Regarding the comparison]
Mhm, it seems no true. [...]
See the other sub-thread where I respond to myself. It can work if
it's modified slightly.

I mean:

if (typeof document.forms[formName]!="undefined"){..}

it isn't slower than:

if (document.forms[formName]){..}
[snip]

But everyone has own coding style, of course.
Precisely. I think that most scripters are (and every scripter should
be) capable of reading
if(object.method) {

as "if 'method' exists as a member of 'object'".

Yes, but is not really correct. This code mean "if method of object is
different to null, undefined, false, empty string or zero".
That's why I see no benefit.

I said, everyone has own coding style. I see benefits.
In fact, I think the verbosity complicates the statement and
makes it more difficult to understand

I not agree. The typeof statement it's more clear. For newbie and not.
 
Z

ZER0

On Mon, 28 Feb 2005 16:46:49 GMT, Michael Winter wrote:

[RG:]
if ( document.forms[formName] != 'undefined'){

Sorry, my english is not very good.
I don't [understand] the reason [for] that comparison.

If you attempt to compare an object to a string [cut]
Rob's suggestion will attempt to compare these
values and obviously, only an undefined property will convert to
'undefined'.

This code doesn't work as you said.
"undefined" value is different to "undefined" string. Check this:

var a={};

alert(a.foo=="undefined");
alert(a.foo==undefined);
/* well this is not works on old browsers, but it just for test */

If you want check for undefined string, you need to use typeof or make a
string cast of "a.foo".

I prefer the first method, as you see.
I suggest you read the ECMAScript specification

I know specification.
 
M

Michael Winter

ZER0 wrote:

[snip]
I mean:

if (typeof document.forms[formName]!="undefined"){..}

it isn't slower than:

if (document.forms[formName]){..}

Oh, I see. Actually, it is but the difference is marginal. It's like
the FAQ notes stating that using unary plus for string-to-number
conversions is faster that all other methods. It's true (there's no
disputing that), but we're talking nanoseconds.

[MLW:]
Yes, but is not really correct. This code mean "if method of object is
different to null, undefined, false, empty string or zero".

In a general context, yes. However, this entire thread has been about
determining the presence of an object. Talking in terms of primitives
is irrelevant. Consider:

var ref = null;

if(document.getElementById) {
ref = document.getElementById('some-id');
}
if(ref) {
/* Use ref */
}

There is no reason to alter that code to use the typeof operator. The
getElementById property will either be undefined or a function
reference and a boolean evaluation will cope with that just fine.
Similarly, the ref variable will either be null or an object reference
(depending on whether some-id exists and the availability of
getElementById). Again, a boolean evaluation suits this perfectly.

The OP's situation is analogous to that presented above: a property
will either be an object reference, or it won't exist (undefined).
Using typeof just isn't necessary.

If we were talking about testing for the presence of primitives, then
of course

if(element.offsetLeft) {

or something similar is inadequate. In fact, so would a comparison
with undefined. The proper approach here would be

if('number' == typeof element.offsetLeft) {

[snip]

Mike
 
Z

ZER0

I mean:
if (typeof document.forms[formName]!="undefined"){..}
it isn't slower than:
if (document.forms[formName]){..}
Oh, I see. Actually, it is but the difference is marginal.

Yes. But the point is: typeof is not slower than "boolean check":

[MLW]
However, both that and a typeof test require a string comparison which
should be slower than the boolean conversion of an object reference, [/MLW]

conversions is faster that all other methods. It's true (there's no
disputing that), but we're talking nanoseconds.

I agree, of course.
In a general context, yes.

In "js engine term", always.
determining the presence of an object. Talking in terms of primitives
is irrelevant. Consider:

var ref = null;

if(document.getElementById) {
ref = document.getElementById('some-id');
}
if(ref) {
/* Use ref */
}

if (ref!=null)

this is correct.

Remember, we talk about "the best method".
getElementById). Again, a boolean evaluation suits this perfectly.

Yes, but is not the perfect method, and the code is more ambiguos than
typeof checking.
Using typeof just isn't necessary.

I'm not agree, sorry. It's a question about good coding style.
Above all if you work in team, or if you work in open source project.

--
ZER0

~ The Tangent Universe collapsed 5966 days, 9 hours, 24 minutes and 42 seconds ago.

on air ~ "See Saw - Edge"
 
M

Michael Winter

ZER0 wrote:

[snip]
[T]he point is: typeof is not slower than "boolean check":

Yes, it is. It might not be by much, but it /is/ slower. Let's not
labour this point. This thread has already dragged on too long.

[snip]

[MLW:]
if (ref!=null)

this is correct.

They are both equally valid in what they attempt to do. Yours is no
more correct than mine.
Remember, we talk about "the best method".

It is better in your opinion. It is not in mine. I do not equate
verbosity with clarity, nor do I feel that it is more correct.

I don't think that either approach can objectively be declared the "best".

[MLW:]
Yes, but is not the perfect method, and the code is more ambiguos than
typeof checking.

You are disagreeing purely on a stylistic basis. Perfect for me, not
for you.

We will just have to agree to disagree. There is nothing factual left
to debate, so let's just drop the conversation, shall we?

Mike
 
D

Dr John Stockton

JRS: In article <Wc%[email protected]>, dated
Tue, 1 Mar 2005 14:44:06, seen in Michael
Winter said:
It's like
the FAQ notes stating that using unary plus for string-to-number
conversions is faster that all other methods. It's true (there's no
disputing that), but we're talking nanoseconds.

I find unary + around 15% faster than subtracting 0, and about 3 times
faster than parseInt.

However, you underestimate the difference; I find parseInt to take 6
microseconds longer, and few users have computers much more than ten
times faster than mine.

The major speed advantages of + are at program-typing time, and in
reducing transmission time of the code !
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top