0

I saw some code that happened in javascript:

var date = +new Date(); //same as 'var date =+ new Date();'

and it gave me a number: 1441863253753 The previous programmer was using this to store unique ids

when I remove the + :

var date = new Date();

it gave me: "Thu Sep 10 2015 01:36:13 GMT-0400 (Eastern Daylight Time)"

can someone tell me what's going on?

I've seen +=, but never =+

sksallaj
  • 3,872
  • 3
  • 37
  • 58
  • take note there is a space there, its `= +new Date()` not `=+`. – Rey Libutan Sep 10 '15 at 05:42
  • adding `+` infront of `new Date()` returns the timestamp _Number_ – Tushar Sep 10 '15 at 05:45
  • @Rey Libutan var a =+ ''; a = 0; I dont thik there is difference between = +new Date() and =+ new Date() – intekhab Sep 10 '15 at 05:47
  • I tried both, and it gave me the same thing.. I looked for this in documentations and googling it, but it's kinda hard looking for something like this.. I knew about unary, but completely forgot about it.. including the term "unary" :-p – sksallaj Sep 10 '15 at 05:50
  • @intekhab, yes there is none but I believe its much clearer when the `+` is closer to the `new Date()` because it has nothing to do with `=`. To avoid the confusion the asker is encountering. – Rey Libutan Sep 10 '15 at 05:51
  • I was gonna make the title "+new" but I thought it was one of those =+ things.. since they were both allowed in javascript – sksallaj Sep 10 '15 at 05:52
  • @Rey I completely agree with you. – intekhab Sep 10 '15 at 05:53
  • A JavaScript date can be written as a string: Thu Sep 10 2015 12:02:54 GMT+0530 (IST) or as a number: 1441866774938 Dates written as numbers, specifies the number of milliseconds since January 1, 1970, 00:00:00. Coming to your question it seams that by adding '+' after assignment operator '=' , converting Date to equal number value. same can be achieve using Number() function, like Number(new Date()); var date = +new Date(); //same as 'var date =number(new Date());' – Dev Sep 10 '15 at 06:47

2 Answers2

1

+ is unary plus operator used to covert the string into number. ex : +'5' // 5 It does same as Number() does in javascript

For more detail see this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus

intekhab
  • 1,566
  • 1
  • 13
  • 19
0

+ converts a value to a number. example:

x = "35"
"35"
y = +x
35
typeof y
"number"
gefei
  • 18,922
  • 9
  • 50
  • 67