Cynial
Cynial

Reputation: 680

What does "i = +i" mean in Javascript?

In jquery source:

eq: function( i ) {
    i = +i;
    return i === -1 ?
        this.slice( i ) :
        this.slice( i, i + 1 );
},

Is it used for make sure parse i to int?

Upvotes: 2

Views: 6587

Answers (5)

mas-designs
mas-designs

Reputation: 7546

+i makes sure that i is parsed into an number.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075059

Yes, applying the unary + to a variable ensures that if it's some other type (a string, for instance), it gets converted to a number (not an int, JavaScript doesn't have ints although it uses them internally for some operations). The number can be fractional, and if it's a string it's parsed in the usual way JavaScript parses numbers (so for instance, +"0x10" is 16 decimal).

Upvotes: 2

Tim Rogers
Tim Rogers

Reputation: 21713

Yes it will make sure it is int (or a number in general as @Felix says). Try this code out:

var i = "2";
console.log(i === 2); // false
console.log(+i === 2); // true

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816790

Is it used for make sure parse i to int?

No, it is to make sure that i is a number (either float or int). Given what the function is doing, it was better to convert i to an non-decimal value though, I'm not sure how slice handles decimals.

More information: MDN - Arithmetic Operators

Upvotes: 5

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385274

Almost, but any number is fine.

[ECMA-262: 11.4.6]: The unary + operator converts its operand to Number type.

The production UnaryExpression : + UnaryExpression is evaluated as follows:

  1. Let expr be the result of evaluating UnaryExpression.
  2. Return ToNumber(GetValue(expr)).

Upvotes: 3

Related Questions