What does = +_ mean in JavaScript

29,516

Solution 1

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

Solution 2

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

Solution 3

=+ 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.

Solution 4

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.

Solution 5

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.

Share:
29,516

Related videos on Youtube

Dimitry
Author by

Dimitry

Tech-leader with fifteen years of experience of setting and leading the tech vision, creating products,architecture and building effective teams (remote and local). Enjoy working on challenging problems, applying ML and Deep Learning, and building products that users love. Blog:Mentful.com Current:Cortex Past:Roundtown and DataXu Some projects: D3 Gantt-Chart Cool D3, Example

Updated on August 15, 2020

Comments

  • Dimitry
    Dimitry over 3 years

    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;
    };
    
    • Oleg
      Oleg about 11 years
      Reminded me of the good old approach operator -->
    • glglgl
      glglgl about 11 years
      What now - =+ or +_? Please be clear about what you try to ask.
    • Kobi
      Kobi about 11 years
      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.
    • Pieter Witvoet
      Pieter Witvoet about 11 years
      The + here is a unary operator, with _ as its operand.
    • Garfield
      Garfield about 11 years
      It's just the negative or positive value as in maths (+10 - positive number), (-10 - negative number). No fancy!
    • Michael Wild
      Michael Wild about 11 years
      Looks like a Perl programmer couldn't let go of the default variable ;-)
    • MC Emperor
      MC Emperor about 11 years
      Just like $ is a valid Java and Javascript identifier, while you just came from PHP programming. Confusing. Ninja it is!
    • hugo der hungrige
      hugo der hungrige about 11 years
      A good syntax-highlighting would have helped you to answer the question.
    • Starx
      Starx about 11 years
      Wonder what the close vote is about?
    • Grijesh Chauhan
      Grijesh Chauhan about 11 years
      Ok, here is good read: Javascript Type-Conversion Second is Type Casting In Javascript
    • Konrad Viltersten
      Konrad Viltersten about 11 years
      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
    • vidya sagar
      vidya sagar about 11 years
      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
    • Admin
      Admin about 11 years
      i hate this kind of variable naming, he/she should be idiot to give such name.
    • tckmn
      tckmn over 10 years
      You can make a smiley face x= +_+ 0;
    • nawfal
      nawfal over 10 years
  • colincameron
    colincameron about 11 years
    Does + really mean cast to a number, or does +_ really mean 0+_, in which case _ must be cast before adding to 0?
  • lonesomeday
    lonesomeday about 11 years
  • Kobi
    Kobi about 11 years
    @c.cam108 - No, they do not behave similarly. Unary plus casts the value to a number, but binary plus does not: +'12' === 12 (result is a number), but 0 + '12' === '012' (result is a string). Note, however, that 0 - '12' === -12.
  • TRiG
    TRiG about 11 years
    +1, as you're the only one here to explicitly point out that _ is a variable.
  • Mathletics
    Mathletics about 11 years
    @TRiG what about Starx' answer, which does so without being tl;dr?
  • Izkata
    Izkata about 11 years
    @juzerali Sure, but that's not good practice. Try using addition ;)
  • Matthew Lock
    Matthew Lock about 11 years
    Looks perlish with perl's default variable $_
  • Attila O.
    Attila O. about 11 years
    You forgot a + before the b.
  • Aki Suihkonen
    Aki Suihkonen about 11 years
    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.
  • Grijesh Chauhan
    Grijesh Chauhan about 11 years
    @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
    Grijesh Chauhan about 11 years
    @Alvin Wong I think X | 0 will be faster then +, not ?
  • Aki Suihkonen
    Aki Suihkonen about 11 years
    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.
  • Grijesh Chauhan
    Grijesh Chauhan about 11 years
    @AkiSuihkonen actually bitwise operators are faster then any other operator. that is the reason!
  • Aki Suihkonen
    Aki Suihkonen about 11 years
    Actually I just tested it jsperf -- 18M ops for '|0', 19M ops for '+'; the performance will probably vary from browser to browser. jsperf.com/strtoint
  • Alvin Wong
    Alvin Wong about 11 years
    @GrijeshChauhan + is faster because it does not perform any other operations on the number (MDN) Also, bitwise OR | only results in an signed integer.
  • Juzer Ali
    Juzer Ali about 11 years
    @Izkata: I know it will concatenate the strings.
  • J.G.Sebring
    J.G.Sebring about 11 years
    @AkiSuihkonen Oh my, just did the jsperf test in Firefox, huge difference.. | alot faster.
  • Grijesh Chauhan
    Grijesh Chauhan about 11 years
    @AlvinWong I don't think so. | is much faster. on most browser. may be slow on IE.
  • Alvin Wong
    Alvin Wong about 11 years
    @GrijeshChauhan Unary + converts to Number but | only result in 32-bit signed integer.
  • Grijesh Chauhan
    Grijesh Chauhan about 11 years
    @AlvinWong Yes true! :)
  • Grijesh Chauhan
    Grijesh Chauhan almost 11 years
    I think in first line you wants to say parseInr(_) instead of parseFloat(_) ?
  • Brian
    Brian almost 11 years
    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.
  • Soner from The Ottoman Empire
    Soner from The Ottoman Empire about 4 years
    String concatenation and conversion is a special feature of the binary plus +. Other arithmetic operators work only with numbers and always convert their operands to numbers.