how JavaScript treats zeros?

G

geoff

Hello

'just a little confused re how JavaScript treats 0 and 00, i.e. 1 zero
and 2 zeros.

Using

var nums = new Array();
nums[0] = 2;
nums[1] = 1;
nums[2] = 0;
nums[3] = 00;
var newcount = 0;
for (count=0;count<4;count++) {
alert(nums[count]);
if (nums[count] != 0 && nums[count] != 00) {
newcount++;
}
}
alert("final newcount = " + newcount);


Three points:

1. 00 is shown as 0 (via alert(nums[count]);)
2. whether I use && or ||

if (nums[count] != 0 && nums[count] != 00) {

or

if (nums[count] != 0 || nums[count] != 00) {

I get the same final newcount value of 2.

'would appreciate comments!

Cheers

Geoff
 
G

geoff

They are exactly the same value: 0. After the script has been parsed,
there is no way to tell the difference. If you want to preserve leading
zeros, you'll need to use a string ("00").

OK - thanks Stefan.

Cheers

Geoff
 
T

Thomas 'PointedEars' Lahn

Stefan said:
They are exactly the same value: 0.

In this particular case, they _evaluate_ to exactly the same value: _+0_
(the existence of a positive and a negative zero in ECMAScript is a
consequence of the Number type being an implementation of IEEE-754 double-
precision floating-point numbers; cf. section 8.5.)

In the general case, though, it is implementation-dependent. Numeric values
that have a leading zero (before the first significant digit) can be
interpreted as octal value in conforming implementations of ECMAScript
Edition 3 and earlier (cf. Editions 1 and 2, section 7.7.3; Edition 3,
Appendix B.1.1), but need to be interpreted as decimal numbers (unless
either an `x' or an `X' follows, in which case they are hexadecimal) in
conforming implementations of ECMAScript Edition 5 (cf. section 7.8.3 which
at the end explicitly forbids this non-normative extension).

There is a grey zone here that makes one want to avoid leading (not
significant) zeroes in numeric values, and to use parseInt(…, desiredBase)
instead of a single-argument parseInt(…) call.

For converting a String value as a decimal representation to Number, the
unary + operator has been suggested as well, as it is assumed that there are
no implementations that convert to octal because the very first ECMAScript
Edition already forbids a string value to be interpreted as octal
representation then (cf. Editions 1 and 2, section 9.3.1; the list item has
been removed from the same section since Edition 3 probably because the
algorithm makes it clear that octal interpretation is out the question).
Still there might be implementations not conforming in that regard. Use
unary + instead of parseInt(…, 10) or parseFloat(…) at your own risk.
After the script has been parsed, there is no way to tell the difference.
If you want to preserve leading zeros, you'll need to use a string ("00").

ACK


PointedEars
 
G

geoff

In this particular case, they _evaluate_ to exactly the same value: _+0_
(the existence of a positive and a negative zero in ECMAScript is a
consequence of the Number type being an implementation of IEEE-754 double-
precision floating-point numbers; cf. section 8.5.)

In the general case, though, it is implementation-dependent. Numeric values
that have a leading zero (before the first significant digit) can be
interpreted as octal value in conforming implementations of ECMAScript
Edition 3 and earlier (cf. Editions 1 and 2, section 7.7.3; Edition 3,
Appendix B.1.1), but need to be interpreted as decimal numbers (unless
either an `x' or an `X' follows, in which case they are hexadecimal) in
conforming implementations of ECMAScript Edition 5 (cf. section 7.8.3 which
at the end explicitly forbids this non-normative extension).

There is a grey zone here that makes one want to avoid leading (not
significant) zeroes in numeric values, and to use parseInt(…, desiredBase)
instead of a single-argument parseInt(…) call.

For converting a String value as a decimal representation to Number, the
unary + operator has been suggested as well, as it is assumed that there are
no implementations that convert to octal because the very first ECMAScript
Edition already forbids a string value to be interpreted as octal
representation then (cf. Editions 1 and 2, section 9.3.1; the list item has
been removed from the same section since Edition 3 probably because the
algorithm makes it clear that octal interpretation is out the question).
Still there might be implementations not conforming in that regard. Use
unary + instead of parseInt(…, 10) or parseFloat(…) at your own risk.


ACK


PointedEars

Thanks Thomas - will read with care.

Cheers

Geoff
 
T

Thomas 'PointedEars' Lahn

Swifty said:
Can the negative zero result from mathematical manipulation, or is it
a theoretical possibility?

Well, if you perform a full text search on the Specification, you can easily
see that -0 and -1 * 0 evaluate to −0, while 1 * 0 and -1 * -0 evaluate to
+0 [11.5.1], and that Math.round(x) returns −0 “If x is less than 0 but
greater than or equal to -0.5†[15.8.2.15], for example. An adjacent note
also states that “The value of Math.round(x) is the same as the value of
Math.floor(x+0.5), except when x is −0 or is less than 0 but greater than or
equal to -0.5; for these cases Math.round(x) returns −0, but
Math.floor(x+0.5) returns +0.â€

On a side note, the SameValue algorithm in Edition 5 [9.12] considers +0 and
−0 to be different values (the return value is `false'), which affects
property access; you may not store +0 in a property that does not have the
[[Writable]] attribute if its current value is −0, and vice versa. So

var foo = {};

Object.defineProperty(foo, "bar", {
value: -1 * 0,
configurable: false,
writable: false
});

Object.defineProperty(foo, "bar", {
value: 0,
writable: false
});

does not change the value of the `bar' property from −0 to +0.
Numeric values that have a leading zero (before the first significant
digit) […] need to be interpreted as decimal numbers (unless either an
`x' or an `X' follows, in which case they are hexadecimal) in conforming
implementations of ECMAScript Edition 5 (cf. section 7.8.3 which
at the end explicitly forbids this non-normative extension).

This is not entirely correct. The Specification is precisely as follows:

| A conforming implementation, when processing strict mode code (see
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| 10.1.1), must not extend the syntax of NumericLiteral to include
| OctalIntegerLiteral as described in B.1.1.

However, the possibility is excluded for parseInt("019") to return 1 as the
leading "0" no longer would indicate that "019" is to be interpreted as an
octal integer "01" followed by "9". Instead, decimal 19 is to be returned
[15.1.2.2]. parseInt("019", 10) or parseFloat("019") is advisable, though.


PointedEars
 
E

Evertjan.

Swifty wrote on 28 mei 2011 in comp.lang.javascript:
Can the negative zero result from mathematical manipulation, or is it
a theoretical possibility?

In programming, a possibility can only be practical,
though it might be small,
all other possibilities being impossible.

In some settings, like meteorology, the concept of negative zero is valid,
but cannot be implemented in the floating point arithmetic of Javascript.

It could perhaps be that a negative zero could legally be stored,
but as it cannot be evaluated nor retrieved in numeric Javascript,
in a programmatical way this remains nonsense.

<script type="text/javascript">
alert( -0 === +0)
</script>

===================

Now how JavaScript treats zeros?

"Treat" in a Javascript sense can only be "evaluate".

Zeros are either part of a litteral string, a string value,
or a part of the script source/text to be evaluated as a floating point
number or a regex ecxpression.

A string value containing one or more zeros can be programmatically,
either explicit or implicit, converted to a numeric value.
 
D

Dr J R Stockton

In comp.lang.javascript message <kvqvt6d0dnevtc558ffuq14lp25kfgaqkb@4ax.
com>, Fri, 27 May 2011 19:29:18, (e-mail address removed) posted:
Cheers

Geoff


It would be helpful if you were to give a full name and a more detailed
address, since otherwise it is hard to tell whether any one instance of
Geoff is or is not the same person as any other. And, in some contexts,
an idea of the person's usual location can be helpful - for example, our
local media have recently indicated the strangeness of .dk.
 
J

Jukka K. Korpela

28.5.2011 11:34 said:
In some settings, like meteorology, the concept of negative zero is valid,
but cannot be implemented in the floating point arithmetic of Javascript.

It has been implemented there.
It could perhaps be that a negative zero could legally be stored,
but as it cannot be evaluated nor retrieved in numeric Javascript,
in a programmatical way this remains nonsense.

Surely it can be evaluated and retrieved. I think you mean it cannot be
distinguished from 0. But that's not true.
alert( -0 === +0)

Shows true, because in normal finite arithmetics and comparisons, 0
behaves like.

But try

alert(1/0);
alert(1/-0);
 
E

Evertjan.

Jukka K. Korpela wrote on 28 mei 2011 in comp.lang.javascript:
It has been implemented there.


Surely it can be evaluated and retrieved. I think you mean it cannot
be distinguished from 0. But that's not true.


Shows true, because in normal finite arithmetics and comparisons, 0
behaves like.

But try

alert(1/0);
alert(1/-0);

Nice.
 
E

Evertjan.

Evertjan wrote on 28 mei 2011 in comp.lang.javascript:
Jukka K. Korpela wrote on 28 mei 2011 in comp.lang.javascript:

Nice.

Still, the inconsequence of:

var temp1 = +0;
var temp2 = -0;
alert(1/temp1 === 1/temp2); // false
alert( temp1 === temp2); // true

returns the usefulness to zero,

Or is my understanding of === as
"do not evaluate before comparing" flawed?
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
In this particular case, they _evaluate_ to exactly the same value: _+0_ ....
In the general case, though, it is implementation-dependent. Numeric values
that have a leading zero (before the first significant digit) can be
interpreted as octal value in conforming implementations of ECMAScript
Edition 3 and earlier (cf. Editions 1 and 2, section 7.7.3; Edition 3,
Appendix B.1.1), but need to be interpreted as decimal numbers (unless
either an `x' or an `X' follows, in which case they are hexadecimal) in
conforming implementations of ECMAScript Edition 5 (cf. section 7.8.3 which
at the end explicitly forbids this non-normative extension).

Actually, it's worse than that. Leading zeros are not allowed by the
ES grammar for number literals, so any interpretation of 00 is outside
the specification. In ES5, it's not allowed to be interpreted as octal,
but the specification doesn't require it to be interpreted as decimal
either. It's perfectly valid for an ECMAScript implementation to throw
a SyntaxError exception instead.

7.8.3 Numeric Literals
Syntax
NumericLiteral ::
DecimalLiteral
HexIntegerLiteral

DecimalLiteral ::
DecimalIntegerLiteral . DecimalDigitsopt ExponentPartopt
. DecimalDigits ExponentPartopt
DecimalIntegerLiteral ExponentPartopt

DecimalIntegerLiteral ::
0
NonZeroDigit DecimalDigitsopt


/L
 
L

Lasse Reichstein Nielsen

Evertjan. said:
Still, the inconsequence of:

var temp1 = +0;
var temp2 = -0;
alert(1/temp1 === 1/temp2); // false
alert( temp1 === temp2); // true

returns the usefulness to zero,

Or is my understanding of === as
"do not evaluate before comparing" flawed?

I don't know what you mean by "evaluate", but it's safer to
think of "===" as: if different types -> false, otherwise
same as ==.

The problem is that numbers are weird. They have
+0 and -0 which are different, but equal according to ==,
and it has NaN which is != itself. But they are all the same
type (number), so == or === does the same thing.

/L
 
T

Thomas 'PointedEars' Lahn

Lasse said:
Actually, it's worse than that. Leading zeros are not allowed by the
ES grammar for number literals, so any interpretation of 00 is outside
the specification.

In a sense. There is still the non-normative Annex B.1.1.
In ES5, it's not allowed to be interpreted as octal,

AISB, that is only true for strict mode code.
but the specification doesn't require it to be interpreted as decimal
either. It's perfectly valid for an ECMAScript implementation to throw
a SyntaxError exception instead. [normative grammar]

ACK, unless it is not strict mode code, and B.1.1 is implemented.


PointedEars
 
L

Lasse Reichstein Nielsen

Thomas 'PointedEars' Lahn said:
Lasse Reichstein Nielsen wrote:

In a sense. There is still the non-normative Annex B.1.1.

True, and that's for all practical purposes outside the specification.
A conformant implementation could just as well extend the language
with heptal numbers as with octal (it's useless, but valid).
AISB, that is only true for strict mode code.

Ack, I was imprecise there.
but the specification doesn't require it to be interpreted as decimal
either. It's perfectly valid for an ECMAScript implementation to throw
a SyntaxError exception instead. [normative grammar]

ACK, unless it is not strict mode code, and B.1.1 is implemented.

Indeed. An implementation could actually decide to allow prefixed
zeros on decimal numbers in strict mode, but not octal numbers.
It would be a different and valid syntax extension, even where
octal literals are not permitted.
I hope nobody will, though :)

/L
 
J

Jukka K. Korpela

29.5.2011 12:09 said:
I don't know what you mean by "evaluate",

In any case, the ECMAScript standard explicitly refers to the evaluation
of operands for the strict equals operator, too. It's not a matter of
evaluating vs. not evaluating +0 and -0 but a matter of definition: by
definition, +0 === -0, even though +0 and -0 are distinct values.
but it's safer to
think of "===" as: if different types -> false, otherwise
same as ==.

Or perhaps more positively: "===" means that the operands are of the
same type and the same. But in the case of +0 and -0, the definitions of
"==" and "===" both explicitly say that the result is true if one of the
operands is +0 and the other is -0. But Infinity and -Infinity are
treated as separate Number values.
The problem is that numbers are weird. They have
+0 and -0 which are different, but equal according to ==,
and it has NaN which is != itself. But they are all the same
type (number), so == or === does the same thing.

Yes, but this makes more sense if you think of the Number type as
reflecting fine-accuracy finite-range floating point calculations rather
than real numbers as a mathematical concept. And the "==" and "==="
operators reflect relations like identity but do not exactly correspond
to any relation outside the language.
 
D

Dr J R Stockton

Sun said:
It has been implemented there.

It MUST be implemented there; the standards require it. That must be
very annoying to anyone implementing JavaScript on a machine without
hardware sign+magnitude floats.

And useful code has been posted here, not so long ago, which depends in
part on the sign of zero.
Surely it can be evaluated and retrieved. I think you mean it cannot be
distinguished from 0. But that's not true.


Shows true, because in normal finite arithmetics and comparisons, 0
behaves like.

But try

alert(1/0);
alert(1/-0);


For all values X of type Number apart from NaN. the sign of X can be
determined by testing the sign of XX = (X + 1/X), which is never of
value zero. That is evidently right, and tested; evaluate XX > 0.

It now occurs to me that time might be saved by evaluating
Neg = -X > 1/X
which is lightly tested, OK
 
D

Dr J R Stockton

In comp.lang.javascript message <n521u6tcjlvshidd4pv4dsufs341j37hpf@4ax.
Can the negative zero result from mathematical manipulation, or is it
a theoretical possibility?

Yes, Y = 1.0 / -Infinity.
Or, indeed, by writing -0 in your code : X = -0 ; Y = 1/X // -Infinity.
I very much doubt that I'd ever use this feature in JavaScript myself
(I struggle with the simplest stuff) but I'm curious.

If you want to convert a fixed-point Hex string (such as "-dead.beef")
to a Number, you can obtain the sign (there are other ways) by reading
the whole string with J = parseInt(S, 16). If "dead" happens to be all
zeroes, then the value of J is minus zero. That was discussed here
fairly recently, to the apparent surprise of one to whom it had to be
pointed out..
 
L

Lasse Reichstein Nielsen

Dr J R Stockton said:
It now occurs to me that time might be saved by evaluating
Neg = -X > 1/X
which is lightly tested, OK

It should work.

-x and 1/x always have opposite signs (because 1/x always have the
same sign as x, and -x always have the opposite), and at most one of
them can be zero, so the > operator should give the correct answer.

/L
 
E

Evertjan.

Dr J R Stockton wrote on 29 mei 2011 in comp.lang.javascript:
It now occurs to me that time might be saved by evaluating
Neg = -X > 1/X
which is lightly tested, OK

What is wrong with:

Neg = x < 0

?
 
J

Jukka K. Korpela

30.5.2011 10:31, Evertjan. kirjoitti:
What is wrong with:

Neg = x < 0

?

It yields false when the value of x is -0.
Ref.: ECMA 262, clause 11.8.5, item 3 g.
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top