mamoo
mamoo

Reputation: 8166

Behavior of JS unary plus operator applied on a string representing a negative hex

according to MDN, when using the unary plus operator:

Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

But when I run this Jasmine test (the toBe() matcher applies a === operator):

   it("should return NaN when trying to convert a string representing a NEGATIVE HEX to the corresponding number", function() {
    var a = '-0xFF';        
    expect(typeof +a).toBe('number');
    expect(isNaN(+a)).toBeTruthy(); //Fails on Chrome and Opera...
  });

It fails on Chrome and Opera (and passes in IE, Safari and Firefox).

Is it a flaw in Chrome and Opera's engines or am I missing something?

Upvotes: 6

Views: 497

Answers (2)

Bergi
Bergi

Reputation: 664375

According to the EcmaScript specification, the unary + operator applies the [String-]to-Number-conversion on the value (here a string), which accepts hex numbers - but not negative hex numbers.

Upvotes: 1

raina77ow
raina77ow

Reputation: 106385

It may - or may not be seen as a flaw, depending on how one's attached to specifications. )

I've found an interesting discussion regarding this behavior. Looks like Firefox was for once in the 'better-than-spec' camp, but then fixed it according to spec.

Upvotes: 2

Related Questions