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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With