adding two quantities

Y

yukatan

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
 
M

Mikhail Esteves

yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:
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

Try:

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

Cheers,
Mikhail
 
E

Evertjan.

Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript:
yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:


Try:

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

Never use eval, it is evil.

Use:

var newStr = 1*s1 + 1*s2

or

var newStr = +s1 + +s2
 
D

Douglas Crockford

Maybe it's a newbie question, but if I have two strings, let's say
Never use eval, it is evil.

Use:

var newStr = 1*s1 + 1*s2

or

var newStr = +s1 + +s2

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;

http://www.crockford.com
 
M

Mikhail Esteves

Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say:
Never use eval, it is evil.

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

Cheers,
Mikhail
 
E

Evertjan.

Mikhail Esteves wrote on 30 okt 2003 in comp.lang.javascript:
Evertjan., on Thu, 30 Oct 2003 20:35:53 +0000, had to say:


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

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 ??
 
M

Mikhail Esteves

Evertjan., on Thu, 30 Oct 2003 20:53:21 +0000, had to say:
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 ??

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



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 :)

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;
}

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.
 
R

Richard Cornford

Because [Warning: unsubstantiated]:

1 it takes a lot of unnecessary processing time.
<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.
 
M

Mikhail Esteves

Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say:
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.

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
 
L

Lee

Mikhail Esteves said:
Richard Cornford, on Thu, 30 Oct 2003 21:32:35 +0000, had to say:


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.

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.
 
R

Richard Cornford

From Googling around, I gather it's evil only when used wrong.

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.
Below is an older (1998) comp.lang.javascript posting:

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.

On Fri, 27 Mar 1998 13:52:38 +0000, Nick Fitzsimons
<[email protected]> wrote:
That said, eval can come in handy for some key things:

1) Backward compatibility with the void function

void was introduced in JavaScript 1.1 and is an operator and not a
function.
function myVoid(stm) {
eval(stm);
}

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.
2) Variable variables
for (i=0;i<5;i++) {
eval ("var var" +i+ " = " i);
}

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.

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

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

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.
 
L

Lasse Reichstein Nielsen

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

I feel a little bad about commenting on something written five years ago.
Mostly because the author won't get to defend his position :)
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.

I never heard that before, and I don't know what the problem is.
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.

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.
That said, eval can come in handy for some key things:

1) Backward compatibility with the void function

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

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

instead of
myVoid("<statements>")
you can use, e.g.:
function(){<statements>}();
or
{statements;undefined}
2) Variable variables
for (i=0;i<5;i++) {
eval ("var var" +i+ " = " i);
}

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.
On the other hand, arrays can be used to achieve a similar effect, but
it isn't exactly the same.

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.
And, eval can come in handy with image swapping, but, there again,
arrays can be used with success as well.

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

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
 
R

Richard Cornford

Are there links to any such tests? As in when, which browser,
what machine and so on these tests were run?

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

The baseless claim that 'eval is evil'
looks like it's been going on for years now.

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.
 
D

Douglas Crockford

From Googling around, I gather it's evil only when used wrong.
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.

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.

http://www.ecmascript.org
 
L

Lasse Reichstein Nielsen

Mikhail Esteves said:
Are there links to any such tests?

I am sure there are several. For the fun of it, I just made my own:
<URL:http://www.infimum.dk/privat/convertTimer.html>
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.
As in when, which browser, what machine and so on these tests were
run?

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.
The baseless claim that 'eval is evil' looks like it's been going on
for years now.

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.
Any info would be appreciated.

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

/L
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
Mikhail Esteves <[email protected]
m> posted at Fri, 31 Oct 2003 01:32:23 :-
yukatan, on Thu, 30 Oct 2003 20:59:09 +0100, had to say:


Try:

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

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.
 

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top