By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,705 Members | 2,017 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,705 IT Pros & Developers. It's quick & easy.

Can I check if an object exists?

P: n/a

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
Jul 23 '05 #1
Share this Question
Share on Google+
23 Replies


P: n/a
On Mon, 28 Feb 2005 10:37:55 GMT, Randell D. wrote:
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 */
}

--
ZER0

~ The Tangent Universe collapsed 5965 days, 5 hours, 2 minutes and 13 seconds ago.

Jul 23 '05 #2

P: n/a
ZER0 wrote:

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


Though

if(document.forms[formName]) {

should be sufficient.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #3

P: n/a
ZER0 wrote:
On Mon, 28 Feb 2005 10:37:55 GMT, Randell D. wrote:

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.
--
Rob
Jul 23 '05 #4

P: n/a
On Mon, 28 Feb 2005 15:00:28 GMT, Michael Winter wrote:

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

if(document.forms[formName]) {

should be sufficient.


Yes, but Randell asks "the best method", and "the best method" is checking
with "typeof".

"if (somevar) " is too generic. This block is not matched for
undefined,null,empty string or zero number.

--
ZER0

~ The Tangent Universe collapsed 5965 days, 9 hours, 36 minutes and 6 seconds ago.

on air ~ "Utada Hikaru - Hikari - PlanitB Remix"
Jul 23 '05 #5

P: n/a
On Tue, 01 Mar 2005 01:10:47 +1000, RobG wrote:
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"
Jul 23 '05 #6

P: n/a
ZER0 wrote:
[...] "the best method" is checking with "typeof".
In certain cases, yes. However, it is not always necessary and that is
true here.
"if (somevar) " is too generic. This block is not matched for
undefined,null,empty string or zero number.


The forms collection isn't some generic thing. Aside from its
predefined properties and methods - length, item, and namedItem - no
other property will evaluate to something other than an object
reference or undefined.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #7

P: n/a
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.

--
Rob
Jul 23 '05 #8

P: n/a
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

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #9

P: n/a
On Tue, 01 Mar 2005 01:49:43 +1000, RobG wrote:
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"
Jul 23 '05 #10

P: n/a
On Mon, 28 Feb 2005 16:07:22 GMT, Michael Winter wrote:
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"
Jul 23 '05 #11

P: n/a
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.

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #12

P: n/a
Michael Winter wrote:
[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

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #13

P: n/a
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

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #14

P: n/a
Randell D. wrote:

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.
Jul 23 '05 #15

P: n/a
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]){..}
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'".
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.

--
ZER0

~ The Tangent Universe collapsed 5966 days, 1 hours, 48 minutes and 11 seconds ago.

Jul 23 '05 #16

P: n/a
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.

--
ZER0

~ The Tangent Universe collapsed 5966 days, 1 hours, 56 minutes and 8 seconds ago.

Jul 23 '05 #17

P: n/a
On Mon, 28 Feb 2005 17:01:47 GMT, Michael Winter wrote:
>> 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.


Infact.

--
ZER0

~ The Tangent Universe collapsed 5966 days, 1 hours, 56 minutes and 28 seconds ago.

Jul 23 '05 #18

P: n/a
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:]
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".


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

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #19

P: n/a
On Tue, 01 Mar 2005 14:44:06 GMT, Michael Winter wrote:
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.
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".

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"
Jul 23 '05 #20

P: n/a
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) {
/* Use ref */
}


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:]
Again, a boolean evaluation suits this perfectly.


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

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #21

P: n/a
Michael Winter wrote:
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. ...

<snip>

My own timings suggest that - typeof - testing is slower than
type-converting tests by between 80 and 500%, depending on the browser
(with the average being at the upper end of that range). That is half an
order of magnitude, a big enough difference for it to be worth a script
authors while to be aware of the difference.

<snip>
if (ref!=null)

this is correct.


They are both equally valid in what they attempt to do.
Yours is no more correct than mine.

<snip>

Indeed, not (type-converting) equal to null is a very particular test
and distinct from both type converting and - typeof - testing. null is
not equal to anything but itself and undefined, not zero, false or the
empty string.

As with all tests the first question is; will the test accurate
discriminate between the possibilities and tell you what you need to
know. After satisfying that other factors, such as the cost and/or
effort involved, might be used to discriminate between available tests.

Richard.
Jul 23 '05 #22

P: n/a
JRS: In article <Wc*****************@text.news.blueyonder.co.uk> , dated
Tue, 1 Mar 2005 14:44:06, seen in news:comp.lang.javascript, Michael
Winter <m.******@blueyonder.co.invalid> posted :
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 !

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #23

P: n/a
On Tue, 01 Mar 2005 16:23:29 GMT, Michael Winter wrote:
[T]he point is: typeof is not slower than "boolean check":
Yes, it is.
Not it isn't.
The benchmark on about 20.000 cycles report the same speed IE/Gecko.
Sometimes the boolean check is a bit faster, sometime the typeof is a bit
faster.
[MLW:] if(ref) {
/* Use ref */
}
if (ref!=null)
this is correct. They are both equally valid in what they attempt to do. Yours is no
more correct than mine.
I'm not agree. The result is the same, but there aren't the same
comparison.
Remember, we talk about "the best method". It is better in your opinion.
Not exactly. Remember the question about coding style and team works.
It's the same reason 'cause it's a good idea use a "notation" for variables
name.
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".
It's your opinion.
[MLW:] Again, a boolean evaluation suits this perfectly.
Yes, but is not the perfect method, and the code is more ambiguos than
typeof checking.

You are disagreeing purely on a stylistic basis.
Not only, but also a js engine viewpoint.
We will just have to agree to disagree. There is nothing factual left
to debate, so let's just drop the conversation, shall we?


Yes, I'm agree. I'm good "orator" but in my mother language. My english is
not so good for explain perfectly my view point and my reasons.

--
ZER0

~ The Tangent Universe collapsed 5967 days, 2 hours, 41 minutes and 17 seconds ago.

on air ~ "See Saw - Edge"
Jul 23 '05 #24

This discussion thread is closed

Replies have been disabled for this discussion.