4

I have come across a refernce to a JavaScript syntax that I don't understand and cannot find any references to online.

[+num]

What does this syntax do and when is it used?

0

1 Answer 1

5

It forces a conversion to a number.

  +'0'; // 0
  +[]; // 0
  +true; // 1
  +false; // 0
  +"I'm Not A Number"; // NaN

From Operators: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Arithmetic_Operators#.2b_(Unary_Plus)

+ (Unary Plus)

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. For example, y = +x takes the value of x and assigns that to y; that is, if x were 3, y would get the value 3 and x would retain the value 3; but if x were the string "3", y would also get the value 3. 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.

Sign up to request clarification or add additional context in comments.

6 Comments

And don't forget that the "non-obvious" ones turn into NaN, e.g. +'abc', +({}), +(function(){}), etc.
@maerics NaN is ironically enough of the type number, so it's still a conversion to a number :) But yes, that's an important observation to be aware of :) I think the OP is asking about the square brackets too, in which case it creates an array with one element containing the number.
@PaulPRO: right, just adding to his examples, since the next question for many people might be "well what about objects?" =)
@maerics Yup, that didn't come out the way I wanted at first. I really just wanted to point out the irony that NaN (not a number) is a number, haha. I like doing that ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.