32

I found the following snippet in the jQuery source code, in the definition of the eq function:

j = +i + ( i < 0 ? len : 0 )

I was surprised by the +i. Rather, I would have expected:

j = i + ( i < 0 ? len : 0 )

What's the difference? What the utility of that leading +?

Shawn
  • 9,389
  • 14
  • 67
  • 113
  • To cast to a number . – NINCOMPOOP Jun 07 '13 at 16:10
  • Oh... I used to use `0+x`... It seems that `+x` is sufficient :) – anishsane Jun 07 '13 at 16:12
  • possible duplicate of [What does = +\_ mean in JavaScript](http://stackoverflow.com/questions/15129137/what-does-mean-in-javascript) and possibly also [Whats the significant use of Unary Plus and Minus operators?](http://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators) – apsillers Jun 07 '13 at 20:03
  • 8
    @anishsane: Not only is `+x` sufficient, but in fact, `0+x` won't generally work, since `+` can perform string concatenation as well as addition. For example, `0+'30'` is `'030'`, and `0+{}` is `'0[object Object]'`. – ruakh Jun 07 '13 at 20:10

3 Answers3

43

+i coerces to number. As an example, try "1" + 1 versus +"1" + 1 (the former is "11" while the latter is 2)

Pero P.
  • 22,259
  • 7
  • 56
  • 79
SheetJS
  • 20,261
  • 12
  • 60
  • 74
33

The plus in front of the variable casts it to a number.

For example:

var x = "12";
console.log(x + 3); //logs 123;
console.log(+x + 3) //logs 15;
tymeJV
  • 99,730
  • 13
  • 150
  • 152
5

I think it's the unary operator: What does the plus sign do in '+new Date'

Basically forced it to be converted to a number.

Community
  • 1
  • 1
Josh P
  • 1,157
  • 13
  • 12