1

I was going through a TypeScript code example and I noticed a special use of the "+" operator in the 3rd line of the code below:

let a: string = "12";
let b: number;
b = +a;
alert(`Result: ${b}`);

It works in TypeScript playground. If you remove the + operator in the 3rd line; you get a TypeScript error.

It seems that the + unary operator converts a string to a number.

I searched google and I am not able to trace any feature like that in neither JavaScript nor TypeScript. Perhaps I am not using the right keyword.

  • What is the name of this feature or concept?
  • Where is this documented?
  • Is this a JavaScript or TypeScript feature?

Update

Thank you, everyone, for help. I am wondering if there is a similar feature for dates as well?

Allan Xu
  • 7,998
  • 11
  • 51
  • 122
  • 3
    Searching for 'javascript unary plus' finds the relevant documentation: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_() – Rob Jul 19 '17 at 00:55
  • In JavaScript it is a common practice to use `+str` to cast `str` to a number. Here's another one to cast a variable to its truth value: `!!obj` – Derek 朕會功夫 Jul 19 '17 at 01:01
  • 2
    More specifically, in [ECMAScript specs](http://www.ecma-international.org/ecma-262/6.0/#sec-unary-plus-operator): "The unary + operator converts its operand to Number type." and "Let *expr* be the result of evaluating *UnaryExpression*. Return ToNumber(GetValue(*expr*))." The thing specific to TypeScript is that it will fail if `b` is assigned a non-number; `+a` is pure JS. – Amadan Jul 19 '17 at 01:05
  • Re: `Date`, see https://stackoverflow.com/q/221539/6680611 – cartant Jul 19 '17 at 01:44
  • @Amadan—love seeing ECMA-262 quoted, but the most recent edition is [*2017* aka ed 8](http://ecma-international.org/ecma-262/8.0/#sec-unary-plus-operator). Hard to keep up wiht annual releases though. ;-) – RobG Jul 19 '17 at 01:55
  • @Amadan, I love to know about this little known, very simple and very helpful tricks. Would you be able to refer me to an article, link or book that list these simple but powerful techniques such as using unary plus or !! ? – Allan Xu Jul 19 '17 at 16:20
  • @RobG, I wanted to add you to the above comment, but it does not let me add more than one contact. Do you know any article? – Allan Xu Jul 19 '17 at 16:22
  • @AllanXu—no, but if you just lurk here looking at code you'll soon pick up a few, like using `||` for *if..else* and `&&` for *if..then*. ;-) – RobG Jul 19 '17 at 23:56
  • @RobG, sounds like a good topic for StackOverflow documentation. The title could be: "JavaScript Cheap Thrills" – Allan Xu Jul 20 '17 at 04:31

0 Answers0