adding two quantities

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Douglas Crockford

    #16
    Re: adding two quantities

    > >From Googling around, I gather it's evil only when used wrong.
    [color=blue]
    > There are no circumstances under which it is _necessary_ to use eval.
    > The few circumstances under which it is appropriate to use eval is where
    > it is necessary to execute JavaScript source code when the contents of
    > that source code cannot be predicted. That is an extremely rare
    > condition and will almost never be the case in a normal Internet
    > browsers scripting context.[/color]
    [color=blue][color=green]
    > >Below is an older (1998) comp.lang.javas cript posting:[/color][/color]

    By Google, the first use of the phrase "eval is evil" in this group was Mar 27,
    1998 by jason olmsted. Clearly, the problems with the misuse of eval have been
    understood for a long time.



    Comment

    • Dr John Stockton

      #17
      Re: adding two quantities

      JRS: In article <pan.2003.10.30 .20.32.23.14851 8@uni-berlin.de>, seen in
      news:comp.lang. javascript, Mikhail Esteves <mail@REMOVETHI S.thejackol.co
      m> posted at Fri, 31 Oct 2003 01:32:23 :-[color=blue]
      >yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:
      >[color=green]
      >> Maybe it's a newbie question, but if I have two strings, let's say s1="4"
      >> and s2="5", how can I get a new string of value "9", that is, add the two
      >> numbers. If I type:
      >> var newStr = s1 + s2
      >> all I get is a concatenation.
      >> How to really add them?
      >> Thx[/color]
      >
      >Try:
      >
      > var newStr = eval(s1) + eval(s2);[/color]

      No-one has given the most generally useful advice, which is "Read the
      FAQ before asking or answering questions here; this one is dealt with
      in Sec 4.21".

      That applies even to the most experienced answerers, who think they know
      everything; if they are right, and do know everything, then they might
      be able to suggest improvements in the FAQ.

      Use of eval is treated in FAQ Sec 4.40, linking to 4.39, linking to
      Cornford on addressing.

      --
      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
      <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
      <URL:http://www.merlyn.demo n.co.uk/js-index.htm> JS maths, dates, sources.
      <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.

      Comment

      • Thomas 'PointedEars' Lahn

        #18
        Re: adding two quantities

        Mikhail Esteves wrote:
        [color=blue]
        > var newStr = eval(s1) + eval(s2);[/color]

        The correct use of eval(...) here is

        var sum = eval("s1 + s2");


        PointedEars

        Comment

        • Thomas 'PointedEars' Lahn

          #19
          Re: adding two quantities

          Evertjan. wrote:
          [color=blue]
          > Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javas cript:[color=green]
          >> var newStr = eval(s1) + eval(s2);[/color]
          >
          > Never use eval, it is evil.[/color]

          eval(...) *is* evil[tm] *unless* used for its intended purpose:




          PointedEars

          Comment

          • Mikhail Esteves

            #20
            Re: adding two quantities

            Thomas 'PointedEars' Lahn, on Fri, 31 Oct 2003 22:30:42 +0100, had to say:
            [color=blue]
            > eval(...) *is* evil[tm] *unless* used for its intended purpose:
            >
            > http://devedge.netscape.com/library/...v.html#1063795[/color]

            All has been said and done :)

            Comment

            • Richard Cornford

              #21
              Re: adding two quantities

              "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
              news:3FA2D461.8 040307@PointedE ars.de...[color=blue][color=green]
              >>var newStr = eval(s1) + eval(s2);[/color]
              >
              >The correct use of eval(...) here is
              >
              > var sum = eval("s1 + s2");[/color]

              Isn't that equivalent to:-

              var sum = s1 + s2;

              and still string concatenation and not numeric addition?

              Richard.


              Comment

              • Lasse Reichstein Nielsen

                #22
                Re: adding two quantities

                "Richard Cornford" <Richard@litote s.demon.co.uk> writes:
                [color=blue]
                > "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                > news:3FA2D461.8 040307@PointedE ars.de...[color=green][color=darkred]
                > >>var newStr = eval(s1) + eval(s2);[/color]
                > >
                > >The correct use of eval(...) here is
                > >
                > > var sum = eval("s1 + s2");[/color][/color]

                ("Correct" by what measure? It is not using eval on a runtime-supplied
                Javascript expression, so by my measure it is wrong).
                [color=blue]
                > Isn't that equivalent to:-
                >
                > var sum = s1 + s2;
                >
                > and still string concatenation and not numeric addition?[/color]

                Yes.

                /L
                --
                Lasse Reichstein Nielsen - lrn@hotpop.com
                DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                'Faith without judgement merely degrades the spirit divine.'

                Comment

                • Lasse Reichstein Nielsen

                  #23
                  Re: adding two quantities

                  Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:
                  [color=blue]
                  > Evertjan. wrote:
                  >[color=green]
                  > > Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javas cript:[color=darkred]
                  > >> var newStr = eval(s1) + eval(s2);[/color]
                  > >
                  > > Never use eval, it is evil.[/color]
                  >
                  > eval(...) *is* evil[tm] *unless* used for its intended purpose:
                  >
                  > http://devedge.netscape.com/library/...v.html#1063795[/color]

                  That description isn't very specific about the intended purpose. The
                  four examples are, however, prime examples of when *not* to use eval.

                  Example 1: eval is simply not needed. This example is only there to
                  show how to write "eval(...)" .

                  Example 2: The "getFieldNa me" function returns the field name. It
                  would be smarter to have a function that returns the field element
                  itself, since you can easily go from element to name. The other
                  direction is harder. They then use eval to go the other direction by
                  using the name as, apparently, a global variable!

                  Example 3: It is just as simple to use a thunk (function with no
                  argument). That will also make the return value explicit instead
                  of the confuzing way the result of the eval is found. Using a function
                  will make syntax errors apparent during loading instead of being hidden
                  until eval is called.
                  I.e.:
                  var delay = function(){if (x==5){alert('x is 42');z=42} else z=0;return z;};
                  document.write( "<P>z is ",delay());

                  Example 4:
                  They use eval to access an object property instead of square bracket
                  notation. It suffers from all the short-commings of Example 3.
                  I.e., an equivalent, but much better solution is:
                  function setValue (textObject, newValue) {
                  document.forms[0][textObject].value = newValue;
                  }

                  If these examples are defining for the intended purpose of eval,
                  then eval is evil when used for its intended purpose.

                  /L
                  --
                  Lasse Reichstein Nielsen - lrn@hotpop.com
                  DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                  'Faith without judgement merely degrades the spirit divine.'

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #24
                    Re: adding two quantities

                    Lasse Reichstein Nielsen wrote:
                    [color=blue]
                    > "Richard Cornford" <Richard@litote s.demon.co.uk> writes:[color=green]
                    >> "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                    >> news:3FA2D461.8 040307@PointedE ars.de...[color=darkred]
                    >> >>var newStr = eval(s1) + eval(s2);
                    >> >
                    >> >The correct use of eval(...) here is
                    >> >
                    >> > var sum = eval("s1 + s2");[/color][/color]
                    >
                    > ("Correct" by what measure?[/color]

                    As the reference shows.
                    [color=blue][color=green]
                    >> Isn't that equivalent to:-
                    >>
                    >> var sum = s1 + s2;
                    >>
                    >> and still string concatenation and not numeric addition?[/color]
                    >
                    > Yes.[/color]

                    No. Please test before you post.


                    PointedEars

                    Comment

                    • Lasse Reichstein Nielsen

                      #25
                      Re: adding two quantities

                      Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:
                      [color=blue]
                      > No. Please test before you post.[/color]

                      I did.
                      ---
                      var s1="4";
                      var s2="5";
                      var sum = eval("s1+s2");
                      alert(sum);
                      ---
                      It alerts "45", not "9".

                      Did you mean to write
                      var sum = eval(s1+"+"+s2) ;
                      ?

                      /L
                      --
                      Lasse Reichstein Nielsen - lrn@hotpop.com
                      DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                      'Faith without judgement merely degrades the spirit divine.'

                      Comment

                      • Richard Cornford

                        #26
                        Re: adding two quantities

                        "Thomas 'PointedEars' Lahn" <PointedEars@we b.de> wrote in message
                        news:3FA37F7E.6 0101@PointedEar s.de...
                        <snip>[color=blue][color=green][color=darkred]
                        >>>>The correct use of eval(...) here is
                        >>>>
                        >>>> var sum = eval("s1 + s2");[/color]
                        >>
                        >> ("Correct" by what measure?[/color]
                        >
                        >As the reference shows.[/color]

                        A reference that illustrates the use of eval by applying it
                        unnecessarily and/or inappropriately . Probably because contriving an
                        illustration of the appropriate use of eval would have taken a couple of
                        pages.
                        [color=blue][color=green][color=darkred]
                        >>> Isn't that equivalent to:-
                        >>>
                        >>> var sum = s1 + s2;
                        >>>
                        >>> and still string concatenation and not numeric addition?[/color]
                        >>
                        >> Yes.[/color]
                        >
                        >No. Please test before you post.[/color]

                        Pot - kettle.

                        <html>
                        <head>
                        <title></title>
                        </head>
                        <body>
                        <script type="text/javascript">
                        //from the OP:-
                        var s1="4";
                        var s2="5";
                        //from your post:-
                        var sum = eval("s1 + s2");
                        document.write( 'sum = '+sum+'<br>'); //output = 45
                        document.write( 'typeof sum = '+(typeof sum));//output = "string"
                        /*
                        Conclusion - var sum = eval("s1 + s2"); - performs string concatenation
                        and not numeric addition. And I was not alone in being able to see that
                        without testing it.
                        */
                        </script>
                        </body>
                        </html>

                        It must be nice to be so confident that you are always right even when
                        contradicted by hard mechanical logic.

                        Richard.


                        Comment

                        • Douglas Crockford

                          #27
                          Re: adding two quantities

                          > >> >>var newStr = eval(s1) + eval(s2);[color=blue][color=green][color=darkred]
                          > >> >
                          > >> >The correct use of eval(...) here is
                          > >> >
                          > >> > var sum = eval("s1 + s2");[/color]
                          > >
                          > > ("Correct" by what measure?[/color]
                          >
                          > As the reference shows.
                          >[color=green][color=darkred]
                          > >> Isn't that equivalent to:-
                          > >>
                          > >> var sum = s1 + s2;
                          > >>
                          > >> and still string concatenation and not numeric addition?[/color]
                          > >
                          > > Yes.[/color]
                          >
                          > No. Please test before you post.[/color]

                          You probably meant to write

                          var sum = eval(s1 + " + " + s2);

                          which is less wrong than your suggestion, but which does two concatenations
                          before invoking the compiler. This is a very bad way to perform addition on two
                          strings.

                          But more instructively, your misplaced confidence in eval() demonstrates that it
                          encourages faulty coding.

                          It is almost always wrong to use eval(). Most of the people using eval() use it
                          wrongly. I cite the above as an example.



                          Comment

                          • Fabian

                            #28
                            I have the answer! (was: Re: adding two quantities)

                            Douglas Crockford hu kiteb:
                            [color=blue]
                            > You probably meant to write
                            >
                            > var sum = eval(s1 + " + " + s2);
                            >
                            > which is less wrong than your suggestion, but which does two
                            > concatenations before invoking the compiler. This is a very bad way
                            > to perform addition on two strings.[/color]

                            I just checked my manual. Apparently, the following should work:

                            var sum = parseFloat(s1) + parseFloat(s2);

                            Im just a disinterested observer though. I just tested it and it seems
                            to work too. Note the capitalisation is important.


                            --
                            --
                            Fabian
                            Visit my website often and for long periods!
                            Penasaran slot depo 10k di AGAM69? Simak pengalaman main Mahjong Ways dan buy spin modal receh yang berakhir manis. Daftar dan buktikan sendiri.


                            Comment

                            • Richard Cornford

                              #29
                              Re: I have the answer! (was: Re: adding two quantities)

                              "Fabian" <lajzar@hotmail .com> wrote in message
                              news:bo1evo$153 r1a$1@ID-174912.news.uni-berlin.de...
                              <snip>[color=blue]
                              >I just checked my manual. Apparently, the following should work:
                              >
                              >var sum = parseFloat(s1) + parseFloat(s2);[/color]
                              [color=blue]
                              >Im just a disinterested observer though. I just tested it and
                              >it seems to work too. Note the capitalisation is important.[/color]

                              The OP specifically stated that the result should be a string
                              representation of the result of the addition of the numeric values
                              represented by the original strings s1 and s2, and your result is
                              numeric, so not quite the whole answer and not substantially different
                              in effectiveness from the code Evertjan posted two days ago.

                              Solutions so far have stressed the importance of first converting the
                              strings s1 and s2 into numbers, for which any of the methods mentioned
                              in the FAQ are effective:-

                              <URL: http://jibbering.com/faq/#FAQ4_21 >

                              Whether parseFloat could be preferred over the other methods would
                              depend on information not included by the OP. parseFloat is certainly
                              slower than any of the methods that force type conversion by applying
                              unambiguously mathematical operators to the strings. On the other hand
                              it scores over those other options in that when presented with an empty
                              string it will return NaN while the type-converting methods return the
                              number zero. When the desire is to perform addition, adding zero when
                              there is no input string may be acceptable/harmless, while accidentally
                              multiplying or dividing by zero may be sufficiently incorrect that a
                              testable NaN result would be preferable. It all depends on the context
                              (and could also be addressed by examining the input strings).

                              Also, if it was known that s1 and s2 were always integers (representable
                              in about 52 bits) it may be possible to use parseInt, and if the integer
                              range was more limited (32 bit signed integers) then it would be
                              possible to consider some bitwise operations as possible additional
                              type-converting methods (though they should not be able to outperform
                              unary plus at forcing type-conversion (and the internal toInt32 function
                              has its own ideas about how to handle unexpected input)).

                              Richard.


                              Comment

                              • Thomas 'PointedEars' Lahn

                                #30
                                Re: adding two quantities

                                Lasse Reichstein Nielsen wrote:
                                [color=blue]
                                > Thomas 'PointedEars' Lahn <PointedEars@we b.de> writes:[color=green]
                                >> No. Please test before you post.[/color]
                                >
                                > I did.
                                > ---
                                > var s1="4";
                                > var s2="5";
                                > var sum = eval("s1+s2");
                                > alert(sum);
                                > ---
                                > It alerts "45", not "9".[/color]

                                /me 2
                                [color=blue]
                                > Did you mean to write
                                > var sum = eval(s1+"+"+s2) ;
                                > ?[/color]

                                No, I had tested with s1 and s2 as number variables. Mea culpa.


                                PointedEars

                                Comment

                                Working...