r/ProgrammerTIL • • Jun 03 '18

Javascript [JavaScript] TIL Unary + operator attempts to converts values to numbers

Surprising example: let x = +new Date() where typeof x => 'number'.

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

Examples:

+3      // 3
+'3'     // 3
+'0xA' // 10
+true  // 1
+false // 0
+null   // 0
+new Date(2018, 1, 1) // 1517464800000
+function(val){  return val } // NaN

- is also a unary operator, but "unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number"

MDN Documentation of Unary +

35 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/philipmat Jun 08 '18
  • always results in a number and |0 always results in an integer.

More TIL - thank you!