I’m reading through a jquery plugin, and find this interesting syntax:
'sth'+ +new Date
It creates a numeric string which the author used for a unique id: sth1237004731731
I’m curious what kind of syntax it is, and if there’s some reading materials about it? Thanks!
It’s using some side effects of JavaScript’s type coercion to build a unique identifier (probably for an element). The confusing part is the
+new Date. Here,new Date(ornew Date()) returns aDateobject. But putting a+or a-in front of this forces the JS interpreter to coerce this value to aNumberobject, and the way JS doesDate>Numberis by returning the timestamp (orgetTime()).So this code could be expressed differently like this:
You might reasonably claim that there’s no need to be so verbose, so I personally would probably have written this as:
However, please avoid coding things like your example if you ever expect someone might have to maintain your code. If it stopped you in your tracks, it probably will stop a lot of people. Coding style is not merely about expressing intent to the interpreter, but expressing intent to human developers. If the code works in the browser but fails with a syntax error in most experienced developers’ heads, you’ve done it wrong, plain and simple.