254

I was wondering what the = +_ operator means in JavaScript. It looks like it does assignments.

Example:

hexbin.radius = function(_) {
   if (!arguments.length)
       return r;
   r = +_;
   dx = r * 2 * Math.sin(Math.PI / 3);
   dy = r * 1.5;
   return hexbin;
};
Starx
  • 72,283
  • 42
  • 174
  • 253
Dimitry
  • 4,284
  • 6
  • 24
  • 40
  • 57
    Reminded me of the good old *approach* operator [`-->`](http://stackoverflow.com/q/1642028/1081234) – Oleg Feb 28 '13 at 07:49
  • What now - `=+` or `+_`? Please be clear about what you try to ask. – glglgl Feb 28 '13 at 08:54
  • 2
    There is no "`=+`" in the question. There's "`= +`", which is very different. `+ =` would not have worked either, that's a syntax error - you cannot ignore spaces here. – Kobi Feb 28 '13 at 09:13
  • 12
    The + here is a unary operator, with _ as its operand. – Pieter Witvoet Feb 28 '13 at 09:47
  • It's just the negative or positive value as in maths (+10 - positive number), (-10 - negative number). No fancy! – Garfield Feb 28 '13 at 14:13
  • 45
    Looks like a Perl programmer couldn't let go of the default variable ;-) – Michael Wild Feb 28 '13 at 14:40
  • Just like `$` is a valid Java and Javascript identifier, while you just came from PHP programming. Confusing. Ninja it is! – MC Emperor Feb 28 '13 at 22:25
  • 4
    A good syntax-highlighting would have helped you to answer the question. – hugo der hungrige Feb 28 '13 at 23:28
  • 3
    Wonder what the close vote is about? – Starx Mar 01 '13 at 03:03
  • Ok, here is good read: [**Javascript Type-Conversion**](http://jibbering.com/faq/notes/type-conversion/) Second is [**Type Casting In Javascript**](http://mahdipedram.com/type-casting-in-javascript/) – Grijesh Chauhan Mar 03 '13 at 08:06
  • 1
    Oh, this was one freaky syntax. Never seen that before and it's got a coolness value of at least 98%. I'm going to use it in the next script just to make people scratch their eyes. :D – Konrad Viltersten Mar 05 '13 at 21:12
  • 1
    I wonder why someone would use just an underscore(`_`) as a variable. Is it to make people scratch their heads while reading his code or he's being simplistic, to reduce the number of chars of the source code? o.O – vidya sagar Mar 06 '13 at 06:51
  • 2
    i hate this kind of variable naming, he/she should be idiot to give such name. –  Mar 26 '13 at 21:16
  • 18
    You can make a smiley face `x= +_+ 0;` – tckmn Aug 20 '13 at 16:44
  • possible duplicate of [What does the plus sign do in 'return +new Date'](http://stackoverflow.com/questions/221539/what-does-the-plus-sign-do-in-return-new-date) – nawfal Jan 10 '14 at 12:33

12 Answers12

401
r = +_;
  • + tries to cast whatever _ is to a number.
  • _ is only a variable name (not an operator), it could be a, foo etc.

Example:

+"1"

cast "1" to pure number 1.

var _ = "1";
var r = +_;

r is now 1, not "1".

Moreover, according to the MDN page on Arithmetic Operators:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. [...] It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

It is also noted that

unary plus is the fastest and preferred way of converting something into a number

Luca Kiebel
  • 8,292
  • 5
  • 24
  • 37
mpm
  • 19,494
  • 7
  • 46
  • 55
95

It is not an assignment operator.

  • _ is just a parameter passed to the function.

    hexbin.radius = function(_) {
                    //       ^ It is passed here
        // ...
    };
    
  • On the next line r = +_; + infront casts that variable (_) to a number or integer value and assigns it to variable r

DO NOT CONFUSE IT WITH += operator

Starx
  • 72,283
  • 42
  • 174
  • 253
54

=+ are actually two operators = is assignment and + and _ is variable name.

like:

i = + 5;
or 
j = + i;
or 
i = + _;

My following codes will help you to show use of =+ to convert a string into int.
example:

y = +'5'
x = y +5
alert(x);

outputs 10

use: So here y is int 5 because of =+
otherwise:

y = '5'
x = y +5
alert(x);

outputs 55

Where as _ is a variable.

_ = + '5'
x = _ + 5
alert(x)

outputs 10

Additionally, It would be interesting to know you could also achieve same thing with ~ (if string is int string (float will be round of to int))

y = ~~'5'  // notice used two time ~
x = y  + 5
alert(x);

also outputs 10

~ is bitwise NOT : Inverts the bits of its operand. I did twice for no change in magnitude.

Grijesh Chauhan
  • 52,958
  • 19
  • 127
  • 190
  • 1
    I use often `x|0` to convert double to int; however this as well as using '~' has the penalty of restricting to numbers < 2^32. +"2e15" does not. – Aki Suihkonen Mar 01 '13 at 06:36
  • @AkiSuihkonen Yes good I believe `x|0` is even faster then `+`. Correct **?** nice technique :). (2) I use `~` just to show OP that `+` is not only a sign can be use (*i myself use `+`*). – Grijesh Chauhan Mar 01 '13 at 06:39
  • Hard to say -- there's jsperf though is one want's to measure it. OTOH these two operators have a complete different meaning. If only requiring a number (and not integer) '+' is anyway one character shorter. – Aki Suihkonen Mar 01 '13 at 06:58
  • @AkiSuihkonen actually bitwise operators are faster then any other operator. that is the reason! – Grijesh Chauhan Mar 01 '13 at 07:16
  • 1
    Actually I just tested it jsperf -- 18M ops for '|0', 19M ops for '+'; the performance will probably vary from browser to browser. http://jsperf.com/strtoint – Aki Suihkonen Mar 01 '13 at 07:31
  • 1
    @AkiSuihkonen Oh my, just did the jsperf test in Firefox, huge difference.. `|` alot faster. – J.G.Sebring Mar 01 '13 at 13:31
16

It's not =+. In JavaScript, + means change it into number.

+'32' returns 32.

+'a' returns NaN.

So you may use isNaN() to check if it can be changed into number.

Ovilia
  • 6,691
  • 11
  • 40
  • 67
16

It's a sneaky one.

The important thing to understand is that the underscore character here is actually a variable name, not an operator.

The plus sign in front of that is getting the positive numerical value of underscore -- ie effectively casting the underscore variable to be an int. You could achieve the same effect with parseInt(), but the plus sign casting is likely used here because it's more concise.

And that just leaves the equals sign as just a standard variable assignment.

It's probably not deliberately written to confuse, as an experienced Javascript programmer will generally recognise underscore as a variable. But if you don't know that it is definitely very confusing. I certainly wouldn't write it like that; I'm not a fan of short meaningless variable names at the best of times -- If you want short variable names in JS code to save space, use a minifier; don't write it with short variables to start with.

SDC
  • 13,745
  • 2
  • 31
  • 48
12

= +_ will cast _ into a number.

So

var _ = "1",
   r = +_;
console.log(typeof r)

would output number.

Harsha Ivaturi
  • 370
  • 2
  • 9
9

I suppose you mean r = +_;? In that case, it's conversion of the parameter to a Number. Say _ is '12.3', then +'12.3' returns 12.3. So in the quoted statement +_ is assigned to r.

KooiInc
  • 104,388
  • 28
  • 131
  • 164
6

_ is just a a variable name, passed as a parameter of function hexbin.radius , and + cast it into number

Let me make a exmple same like your function .

var hexbin = {},r  ;

hexbin.radius = function(_) {
   if (!arguments.length)
      return r;
   console.log( _ , typeof _ )    
   r = +_;
   console.log( r , typeof r , isNaN(r) );   
}

and run this example function .. which outputs

hexbin.radius( "1");

1 string
1 number false 

hexbin.radius( 1 );

1 number
1 number false

hexbin.radius( [] );

[] object
0 number false

hexbin.radius( 'a' );

a string
NaN number true

hexbin.radius( {} );

Object {} object
NaN number true

hexbin.radius( true );

true boolean
1 number false
rab
  • 3,942
  • 1
  • 27
  • 40
5

It Will assign new value to left side variable a number.

var a=10;
var b="asg";
var c=+a;//return 10
var d=-a;//return -10
var f="10";

var e=+b;
var g=-f;

console.log(e);//NAN
console.log(g);//-10
Amrendra
  • 1,981
  • 2
  • 15
  • 34
4

Simply put, +_ is equivalent to using the Number() constructor.

In fact, it even works on dates:

var d = new Date('03/27/2014');
console.log(Number(d)) // returns 1395903600000
console.log(+d) // returns 1395903600000

DEMO: http://jsfiddle.net/dirtyd77/GCLjd/


More information can also be found on MDN - Unary plus (+) section:

The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.

Dom
  • 32,648
  • 12
  • 45
  • 77
3

+_ is almost equivalent of parseFloat(_) . Observe that parseInt will stop at non numeric character such as dot, whereas parshFloat will not.

EXP:

    parseFloat(2.4) = 2.4 
vs 
    parseInt(2.4) = 2 
vs 
    +"2.4" = 2.4

Exp:

var _ = "3";
    _ = +_;

console.log(_); // will show an integer 3

Very few differences:

Community
  • 1
  • 1
Brian
  • 4,623
  • 8
  • 35
  • 54
  • I think in first line you wants to say `parseInr(_)` instead of `parseFloat(_)` **?** – Grijesh Chauhan Jul 20 '13 at 09:11
  • 1
    No I meant `float`, because parseInt will stop at non numeric character, parshFloat will not. EXP: `parseFloat(2.4) = 2.4` vs `parseInt(2.4) = 2`. – Brian Jul 20 '13 at 09:58
2

In this expression:

r = +_;
  • '+' acts here as an unary operator that tries to convert the value of the right operand. It doesn't convert the operand but the evaluated value. So _ will stay "1" if it was so originally but the r will become pure number.

Consider these cases whether one wants to apply the + for numeric conversion

+"-0" // 0, not -0
+"1" //1
+"-1" // -1
+"" // 0, in JS "" is converted to 0
+null // 0, in JS null is converted to 0
+undefined // NaN
+"yack!" // NaN
+"NaN" //NaN
+"3.14" // 3.14

var _ = "1"; +_;_ // "1"
var _ = "1"; +_;!!_ //true
var _ = "0"; +_;!!_ //true
var _ = null; +_;!!_ //false

Though, it's the fastest numeric converter I'd hardly recommend one to overuse it if make use of at all. parseInt/parseFloat are good more readable alternatives.

Arman
  • 4,547
  • 3
  • 30
  • 33