"" + some form value

Discussion in 'Javascript' started by Gene Wirchenko, Nov 18, 2011.

  1. Dear JavaScripters:

    What does "" + some form value do? For example,
    ""+document.Contest.Last.value
    Won't document.Contest.Last.value be string regardless? I tried
    forcing one such to a number, and after the assignment, typeof()
    reported it was a string.

    Is this ""+ a bit of superstition, or am I missing something?

    Sincerely,

    Gene Wirchenko
     
    Gene Wirchenko, Nov 18, 2011
    #1
    1. Advertisements

  2. There is no consensus on what is most runtime-efficient here. In fact, the
    results at <http://jsperf.com/string-conversion-speed> vary so much between
    implementations, runtime environments, and even consecutive tests in the
    very same runtime environment, and String() is indeed self-documenting, that
    I am going to keep my original, ECMAScript-supported approach¹ of using
    String() when I do not know the type of the value and if it(s object
    representation) has a toString() method.


    PointedEars
    ___________
    ¹) the `+' operator requires more algorithmic steps for the type conversion
    than String()
     
    Thomas 'PointedEars' Lahn, Nov 19, 2011
    #2
    1. Advertisements

  3. In comp.lang.javascript message <fuodc799nhk0c9ofihe817rjtkjid2cq79@4ax.
    Not inevitably.

    document.Contest = {} ;
    document.Contest.Last = {} ;
    document.Contest.Last.value = new Date() ;
    99 ;
    document.Contest.Last.value.getHours() ;

    gives me 18 (YMMV)
    It ensures a string value; for example, this

    var U ; typeof ( ''+U) // gives 'string'
    typeof (+''+U) // gives 'number'
    typeof (''+ +U) // gives 'string'

    Some coders find it easier to force a string rather than to become
    confident that it is and always will be inevitably a string already.
     
    Dr J R Stockton, Nov 19, 2011
    #3
  4. I think I will, too.
    With an assignment statement. The following statement was an
    alert() to get the typeof() and reported string.

    [snip]
    No, definitely a form element. That is why I was puzzled about
    it.

    Sincerely,

    Gene Wirchenko
     
    Gene Wirchenko, Nov 20, 2011
    #4
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.