adding two quantities

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

    adding two quantities

    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


  • Mikhail Esteves

    #2
    Re: adding two quantities

    yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:
    [color=blue]
    > 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);

    Cheers,
    Mikhail

    Comment

    • Evertjan.

      #3
      Re: adding two quantities

      Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javas cript:
      [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]

      Never use eval, it is evil.

      Use:

      var newStr = 1*s1 + 1*s2

      or

      var newStr = +s1 + +s2





      --
      Evertjan.
      The Netherlands.
      (Please change the x'es to dots in my emailaddress)

      Comment

      • Douglas Crockford

        #4
        Re: adding two quantities

        > >> Maybe it's a newbie question, but if I have two strings, let's say[color=blue][color=green][color=darkred]
        > >> 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.[/color]
        > > var newStr = eval(s1) + eval(s2);[/color][/color]
        [color=blue]
        > Never use eval, it is evil.
        >
        > Use:
        >
        > var newStr = 1*s1 + 1*s2
        >
        > or
        >
        > var newStr = +s1 + +s2[/color]

        The last form is definitely the best. I recommend adding parens to it

        var newStr = +s1 + (+s2);

        so that it will not be confused with

        var newStr = +s1 ++s2;



        Comment

        • Mikhail Esteves

          #5
          Re: adding two quantities

          Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say:
          [color=blue]
          > Never use eval, it is evil.[/color]

          I've heard this before. But why exactly is it evil?

          Cheers,
          Mikhail

          Comment

          • Evertjan.

            #6
            Re: adding two quantities

            Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javas cript:
            [color=blue]
            > Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say:
            >[color=green]
            >> Never use eval, it is evil.[/color]
            >
            > I've heard this before. But why exactly is it evil?
            >[/color]

            Because [Warning: unsubstantiated]:

            1 it takes a lot of unnecessary processing time.
            [I think to set up a new instance of javascript]

            2 if you make an code error the errorhandling will be hazardous.

            Anyone that knows more about these evils ??

            --
            Evertjan.
            The Netherlands.
            (Please change the x'es to dots in my emailaddress)

            Comment

            • Mikhail Esteves

              #7
              Re: adding two quantities

              Evertjan., on Thu, 30 Oct 2003 20:53:21 +0000, had to say:
              [color=blue]
              > Because [Warning: unsubstantiated]:
              >
              > 1 it takes a lot of unnecessary processing time.
              > [I think to set up a new instance of javascript]
              >
              > 2 if you make an code error the errorhandling will be hazardous.
              >
              > Anyone that knows more about these evils ??[/color]

              From Googling around, I gather it's evil only when used wrong. Below is
              an older (1998) comp.lang.javas cript posting:



              On Fri, 27 Mar 1998 13:52:38 +0000, Nick Fitzsimons
              <nickfitzsimons @atlasinteracti ve.com> wrote:
              [color=blue]
              >Mike Shaver wrote:[color=green]
              >>
              >> Christopher Thompson wrote:[color=darkred]
              >> > Try using eval().[/color]
              >>
              >> No! Don't use eval! Eval is evil, and should be used only in the
              >> direst of circumstances! Bad Christopher![/color]
              >
              >Mike, I know that eval was buggy or totally non-functional on certain NN
              >2 versions/platforms, but I'd never thought of it as being actually
              >*evil* - can you expand a little on your chastisement of Christopher, as
              >although I almost never use eval myself, I don't want to stray too far
              >from the path of righteousness - well, not in my coding, anyway :-)
              >[/color]

              Who knows what crawled up Mike's ass in this statement, but I know I
              wouldn't categorize eval as evil (maybe he liked the pun :-). It has
              been quite annoying for some who did not use it correctly with respect
              to the platform, or who overused it, but it can be really handy at
              times.

              First, elaboration of the above

              1) IE - must be the full line. There are so many variations to this
              damn browser that I am sure there are exceptions, but the safe rule is
              to only use eval for a complete statement.

              2) Overuse - eval is apparently much slower than it ought to be, I
              haven't run any benchmarks, but others have indicated this to be so,
              so overuse means performance hits. Bad enough that the browser may be
              living on a 486 with <= 16M Ram that you shouldn't add insult to
              injury.

              That said, eval can come in handy for some key things:

              1) Backward compatibility with the void function

              function myVoid(stm) {
              eval(stm);
              }

              2) Variable variables
              for (i=0;i<5;i++) {
              eval ("var var" +i+ " = " i);
              }

              On the other hand, arrays can be used to achieve a similar effect, but
              it isn't exactly the same.

              var vars = new Array();
              for (i=0;i<5;i++) {
              vars[i] = i;
              }

              And, eval can come in handy with image swapping, but, there again,
              arrays can be used with success as well.

              The gist is that while they aren't evil, they should be used, as Mike
              indicated, with moderation.

              Comment

              • Richard Cornford

                #8
                Re: adding two quantities

                "Evertjan." <exjxw.hannivoo rt@interxnl.net > wrote in message
                news:Xns9424DEB 6214CDeejj99@19 4.109.133.29...
                <snip>[color=blue]
                > Because [Warning: unsubstantiated]:
                >
                > 1 it takes a lot of unnecessary processing time.[/color]
                <snip>

                Testing the speed of various string to number type converting operations
                revealed that the use of - evel - is about 40 times slower than forcing
                type conversion with the unary plus operator and at least 5 times slower
                than the worst or the other alternatives. It is also the only string to
                number type converting method that has unpredictable output if the input
                is not a string representation of a number.

                Richard.


                Comment

                • Mikhail Esteves

                  #9
                  Re: adding two quantities

                  Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say:
                  [color=blue]
                  > Testing the speed of various string to number type converting operations
                  > revealed that the use of - evel - is about 40 times slower than forcing
                  > type conversion with the unary plus operator and at least 5 times slower
                  > than the worst or the other alternatives. It is also the only string to
                  > number type converting method that has unpredictable output if the input
                  > is not a string representation of a number.[/color]

                  Are there links to any such tests? As in when, which browser, what machine
                  and so on these tests were run? The baseless claim that 'eval is evil'
                  looks like it's been going on for years now.

                  Any info would be appreciated.

                  Mikhail

                  Comment

                  • Richard Cornford

                    #10
                    Re: adding two quantities

                    "Mikhail Esteves" <mail@REMOVETHI S.thejackol.com > wrote in message
                    news:pan.2003.1 0.30.21.03.54.2 74940@uni-berlin.de...
                    <snip>[color=blue]
                    >From Googling around, I gather it's evil only when used wrong.[/color]

                    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=blue]
                    >Below is an older (1998) comp.lang.javas cript posting:[/color]

                    That was a very long time ago. Netscape 4 and IE 4 were brand new and
                    some kludge workarounds might have been needed or really ancient
                    browsers. These days anyone attempting to use a browser much older than
                    Netscape 4 on the Internet is not finding the experience at all
                    productive.

                    [color=blue]
                    > On Fri, 27 Mar 1998 13:52:38 +0000, Nick Fitzsimons
                    > <nickfitzsimons @atlasinteracti ve.com> wrote:[/color]
                    <snip>[color=blue]
                    > That said, eval can come in handy for some key things:
                    >
                    > 1) Backward compatibility with the void function[/color]

                    void was introduced in JavaScript 1.1 and is an operator and not a
                    function.
                    [color=blue]
                    > function myVoid(stm) {
                    > eval(stm);
                    > }[/color]

                    This function in no way mimics the action of the void operator (even if
                    it was treated as a function) and seems very likely to generate a run
                    time error if used in the place of the void operator. Simply using -
                    function myVoid(param){ return; } - would be a better substitute for the
                    void operator.
                    [color=blue]
                    > 2) Variable variables
                    > for (i=0;i<5;i++) {
                    > eval ("var var" +i+ " = " i);
                    > }[/color]

                    This is simply unnecessary if the variable in question is a global
                    variable. In any event, the functionality of dynamically creating
                    function local named references to values can easily be achieved by
                    other means, and the result will be more efficient than this eval
                    aproach.

                    <snip>[color=blue]
                    >And, eval can come in handy with image swapping, but,
                    >there again, arrays can be used with success as well.[/color]

                    I just don't see this. If it was true 5 years ago it certainly is not
                    relevant now.
                    [color=blue]
                    > The gist is that while they aren't evil, they should be used,
                    >as Mike indicated, with moderation.[/color]

                    eval does not need to be used in moderation, it should be used _only_
                    when it is appropriate. But that will be so infrequently that any desire
                    to use it in code should be looked upon as indicative of the author
                    missing a better (usually much better) alternative.

                    Richard.


                    Comment

                    • Lasse Reichstein Nielsen

                      #11
                      Re: adding two quantities

                      Mikhail Esteves <mail@REMOVETHI S.thejackol.com > writes:
                      [color=blue]
                      > From Googling around, I gather it's evil only when used wrong. Below is
                      > an older (1998) comp.lang.javas cript posting:[/color]

                      I feel a little bad about commenting on something written five years ago.
                      Mostly because the author won't get to defend his position :)
                      [color=blue]
                      > First, elaboration of the above
                      >
                      > 1) IE - must be the full line. There are so many variations to this
                      > damn browser that I am sure there are exceptions, but the safe rule is
                      > to only use eval for a complete statement.[/color]

                      I never heard that before, and I don't know what the problem is.
                      [color=blue]
                      > 2) Overuse - eval is apparently much slower than it ought to be, I
                      > haven't run any benchmarks, but others have indicated this to be so,
                      > so overuse means performance hits. Bad enough that the browser may be
                      > living on a 486 with <= 16M Ram that you shouldn't add insult to
                      > injury.[/color]

                      This is still the case, except perhaps for the "ought to". Eval is
                      slow! It is not surpricing, since it has to parse the string before
                      evaluating it.
                      [color=blue]
                      > That said, eval can come in handy for some key things:
                      >
                      > 1) Backward compatibility with the void function
                      >
                      > function myVoid(stm) {
                      > eval(stm);
                      > }[/color]

                      "void" is not a function, but an operator. There are lots of different
                      ways to do the same thing without eval.

                      instead of
                      myVoid("<statem ents>")
                      you can use, e.g.:
                      function(){<sta tements>}();
                      or
                      {statements;und efined}
                      [color=blue]
                      > 2) Variable variables
                      > for (i=0;i<5;i++) {
                      > eval ("var var" +i+ " = " i);
                      > }[/color]

                      BAD coding style. Very! Sure, you can do it, but you shouldn't.

                      Make one variable containing an array. That is probably what you needed
                      to begin with.
                      [color=blue]
                      > On the other hand, arrays can be used to achieve a similar effect, but
                      > it isn't exactly the same.[/color]

                      No, it's far better. Doing it with eval will also mean that you need
                      eval to reference the variables - eval("var"+i) - so there is no reason
                      not to use an array instead.
                      [color=blue]
                      > And, eval can come in handy with image swapping, but, there again,
                      > arrays can be used with success as well.[/color]

                      I can't see how eval can do anything that an array can't do better.
                      [color=blue]
                      > The gist is that while they aren't evil, they should be used, as Mike
                      > indicated, with moderation.[/color]

                      I disagree. They should be used only when *absolutely* necessary, i.e.,
                      when you need to evaluate Javascript code supplied as a string (most likely
                      as input by a user or fetched over the net).

                      Very few people write pages where eval is necessary.

                      /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

                      • Lee

                        #12
                        Re: adding two quantities

                        Mikhail Esteves said:[color=blue]
                        >
                        >Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say:
                        >[color=green]
                        >> Testing the speed of various string to number type converting operations
                        >> revealed that the use of - evel - is about 40 times slower than forcing
                        >> type conversion with the unary plus operator and at least 5 times slower
                        >> than the worst or the other alternatives. It is also the only string to
                        >> number type converting method that has unpredictable output if the input
                        >> is not a string representation of a number.[/color]
                        >
                        >Are there links to any such tests? As in when, which browser, what machine
                        >and so on these tests were run? The baseless claim that 'eval is evil'
                        >looks like it's been going on for years now.
                        >
                        >Any info would be appreciated.[/color]

                        Why do you assume that it's baseless?
                        It should be obvious to anybody who understands what eval() does
                        that it's going to take a lot longer to compile an expression and
                        evaluate it than to evaluate a precompiled expression.

                        You can create your own time comparison with a few lines of code.

                        Comment

                        • Mikhail Esteves

                          #13
                          Re: adding two quantities

                          Lee, on Thu, 30 Oct 2003 14:36:16 -0800, had to say:
                          [color=blue]
                          > Why do you assume that it's baseless?[/color]

                          Me bad. That was a genuine mistake :)

                          Comment

                          • Richard Cornford

                            #14
                            Re: adding two quantities

                            "Mikhail Esteves" <mail@REMOVETHI S.thejackol.com > wrote in message
                            news:pan.2003.1 0.30.22.26.41.1 58647@uni-berlin.de...[color=blue][color=green]
                            >>Testing the speed of various string to number type converting
                            >>operations revealed that the use of - evel - is about 40 times
                            >>slower than forcing type conversion with the unary plus operator
                            >>and at least 5 times slower than the worst or the other
                            >>alternative s. ...[/color][/color]
                            <snip>[color=blue]
                            >
                            >Are there links to any such tests? As in when, which browser,
                            >what machine and so on these tests were run?[/color]

                            Try it for yourself, any browser. The machine is not important when
                            gathering relative speed values:-

                            <URL: http://www.litotes.demon.co.uk/js_sp...gToNumber.html >
                            [color=blue]
                            >The baseless claim that 'eval is evil'
                            >looks like it's been going on for years now.[/color]

                            eval is evil and always has been. This group continues to actively
                            campaign against its abuse because it server to discourage new script
                            authors from learning to do things properly. People promote eval because
                            it "works", in the broadest possible sense of the word, but is its use
                            correct? Take the code you posted to this thread:-

                            var newStr = eval(s1) + eval(s2);

                            Apart from the fact that, when it "works", it still does not fulfil the
                            OPs requirement as the output is of numeric type and not a string, which
                            brings into question the use of "newStr" as an identifier for the
                            result. The eval function may react in almost any way if the s1 or s2
                            values are no actually strings that represent numbers in JavaScript
                            source code. When so many alternative string to number type-converting
                            methods exist and they _all_ have predictable, specified and documented
                            output if the input does not happen to be a string representation of a
                            number, then eval is objectively the worst string to number
                            type-converting method to use. So why promote its use? Because it
                            "works" (when it works)?

                            But eval abuse does not only shelter people from learning better
                            techniques, it also encourages a "mystical incantation" approach to
                            programming, resulting in people wrapping the eval function around all
                            sorts of weird and wonderful expressions, and because doing that won't
                            necessarily make things worse and will often mask errors this habit
                            propagates throughout their code.

                            No one benefits from the use of eval, not the user (burdened with slow,
                            processor intensive code and excessive downloads), not the programmer
                            (screened from learning to do their job well) and definitely not the
                            posters on this group. If that results in a pejorative epithet being
                            attached to the eval function then that is not really surprising.

                            Richard.


                            Comment

                            • Lasse Reichstein Nielsen

                              #15
                              Re: adding two quantities

                              Mikhail Esteves <mail@REMOVETHI S.thejackol.com > writes:
                              [color=blue]
                              > Are there links to any such tests?[/color]

                              I am sure there are several. For the fun of it, I just made my own:
                              <URL:http://www.infimum.dk/privat/convertTimer.ht ml>
                              It lets you test for yourself. On my machine, with the default settings,
                              IE and Opera are both approximatly 80 times slower using eval than using
                              unary plus. In Netscape 4 and Mozilla, the difference is only 9 times.
                              [color=blue]
                              > As in when, which browser, what machine and so on these tests were
                              > run?[/color]

                              Mine is a 1GHz Athlon running Windows XP Pro. I did a quick test in Opera 7.21,
                              IE 6, Mozilla FB 0.7 and Netscape 4.80.
                              [color=blue]
                              > The baseless claim that 'eval is evil' looks like it's been going on
                              > for years now.[/color]

                              It's not baseless. It's always been evil :)

                              My primary problems with using eval are:

                              1) Using it doesn't adequatly separate code and data. This makes bugs
                              easier to make and harder to find.

                              2) It is too powerful a tool most of the jobs it is used for, making
                              it too easy to shoot oneself in the foot.

                              3) There are other, simpler and more specialized, tools to do the same
                              jobs.
                              [color=blue]
                              > Any info would be appreciated.[/color]

                              You mean that you are not certain that the claims are baseless? :)

                              /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

                              Working...