Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 474
mamoo Avatar asked Apr 27 '12 09:04

mamoo


People also ask

What does unary plus operator do to string representations of integers?

It can convert string representations of integers and floats, as well as the non-string values true , false , and null . Integers in both decimal and hexadecimal ( 0x -prefixed) formats are supported. Negative numbers are supported (though not for hex). Using the operator on BigInt values throws a TypeError.

What is the unary operator in JavaScript?

A unary operation is an operation with only one operand. This operand comes either before or after the operator. Unary operators are more efficient than standard JavaScript function calls. Additionally, unary operators can not be overridden, therefore their functionality is guaranteed.

What is unary plus operator?

The + (unary plus) operator maintains the value of the operand. The operand can have any arithmetic type or pointer type. The result is not an lvalue. The result has the same type as the operand after integral promotion. Note: Any plus sign in front of a constant is not part of the constant.

Is Typeof a unary operator JavaScript?

7. type of. type of is a unary operand which returns a string indicating that the data type of the operand is a string which makes use of operators which comes before the operand.


2 Answers

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.

like image 106
raina77ow Avatar answered Sep 27 '22 23:09

raina77ow


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.

like image 30
Bergi Avatar answered Sep 27 '22 22:09

Bergi