The unary plus operator

The unary plus operator (+...) will convert its operand into Number as if it were passed to Number(...):

+'42'; // => 42
+({ valueOf() { return 42; } });

To do this, our cherished internal ToPrimitive procedure will be utilized, as discussed in the last chapter, in the Conversion to a primitive section. Its result will then be re-coerced into Number if it is not already Number. So, if ToPrimitive were to return String, that String would be converted into Number, meaning that non-numeric strings will result in NaN:

+({ toString() { return 'not a number'; } }); // => NaN

And naturally, if String from ToPrimitive can be converted into Numberthen that is what the unary + operator will evaluate to:

+({ toString() { return '12345'; } }); // => 12345

This is more realistically observed when coercing an array via +:

+['5e3']; // => 5000

// Equivalent to:
Number(String(['5e3'])); // => 5000

The unary + operator is usually used in places where a programmer wishes to cast a number-like object to Number so that they can then use it with other numeric operations. Usually, however, it is preferable to explicitly use Number(...) as it is much clearer what the intention is.

The unary + operator can sometimes be confused with other operations. Consider this scenario:

number + +someObject

To someone unfamiliar with the unary plus or someone not attuned to seeing it regularly, this code may look like it contains a typo. We could potentially wrap the entire unary operation in its own parentheses to make it clearer:

number + (+someObject)

Or we could instead use the much clearer Number(...) function:

number + Number(someObject)

In summary, the unary + operator is a convenient shortcut to Number(...). It's useful and quick, though in most cases, we should prefer to communicate our intent more clearly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.119.199