0

I came across some weird JavaScript code:

var a, b; // integers set somewhere;

var c = +b;

someFunc(+a);

What does that + mean here? In my tests I cannot see any effect from it in JavaScript, but at the same time it is valid JavaScript.

What is it really, and why would anyone ever use it?

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • 3
    [see documentation on unary +](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()) – Kevin L Jul 19 '16 at 17:32

2 Answers2

3

It is a unary operator. It converts the value to a Number, if it can.

+'4' === 4

+'4.23' === 4.23

+'true' === 1

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Arithmetic_operators

Jordan
  • 902
  • 2
  • 10
  • 37
2

It converts the value to a Number

William B
  • 1,411
  • 8
  • 10