ArslArsl ArslArsl - 1 month ago 10
Javascript Question

Js object key: plus value syntax

I found this weird syntax in d3 example

var heatmapChart = function(tsvFile) {
d3.tsv(tsvFile,
function(d) {
return {
day: +d.day,
hour: +d.hour,
value: +d.value
};
},


What plus in

day: +d.day,


mean?

Answer

This is a unary conversion. It's a shorthand method to convert to a number. From the ECMAScript docs:

The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

Let expr be the result of evaluating UnaryExpression.

Return ToNumber(GetValue(expr)).

var a = "45"; //typeof String
a = +a; // now typeof Number
Comments