Gene Wirchenko wrote:
> Dear JavaScripters:
>
> What does "" + some form value do? For example,
The addition operator does string concatenation if either of its
argument is a string primitive, as in this case. However, when it does
string concatenation and non-string argument (the right hand side in
this case) is type-converted into a string primitive (by applying the
language's type conversion rules). It is this type-conversion that
usually motivates the concatenation of an empty string, that is, the
result is just the result of type converting the right hand side into a
string primitive, as concatenating an empty string has no effect on that
result.
> ""+document.Contest.Last.value
Assuming that - document.Contest.Last.value - if a reference to the -
value - property of a form element then the concatenation is actually
worthless as such - value - property values are already string
primitives. Unfortunately forced type-conversion methods often ends up
being applied as a mystical incantation, and so in contexts where they
actually have no effect.
Incidentally, to force type conversion to a string primitive the String
constructor can be used without the - new - operator, as in:-
String(document.Contest.Last.value)
- Which has been both recommended against on the grounds that it could
be confused with a miss-typed - new String(s); - and recommended as a
self-documenting and explicit means of forcing type-conversion to a
string. I am leaning towards the latter. Concatenating the empty string
has been shown to be the most runtime efficient type-conversion to
string primitive operation.
> Won't document.Contest.Last.value be string regardless?
Yep.
> I tried forcing one such to a number,
How? Strings can be type-converted into number primitive values using,
say, +string or Number(string) (and commonly in the past or
string*1 , or string-0 ).
> and after the assignment, typeof()
> reported it was a string.
>
> Is this ""+ a bit of superstition, or am I missing something?
No, it appears to be superstition in this case. Though there is a slight
possibility that - document.Contest.Last - was not referring to a form
element in this case (then you only have evidence of poor code design
rather than a mystical incantation).
Richard.