0

Why does the following snippet of code convert my variable of type string to type number?

let stringInteger = '42';
let convertToInteger = +stringInteger;
console.log(typeof convertToInteger)

More specifically, why does prefixing + to the variable have this effect? Note, I'm asking why not what it does.

James Marino
  • 668
  • 1
  • 9
  • 25
  • 3
    Possible duplicate of [What does = +\_ mean in JavaScript](https://stackoverflow.com/questions/15129137/what-does-mean-in-javascript) – Romeo Sierra May 07 '18 at 02:12

2 Answers2

2

It's the Unary Plus Operator.

Your question is answered here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_()

Daniel
  • 1,125
  • 2
  • 9
  • 21
1

It's called a Unary Plus operator. It basically tries to convert non-integer variables into integers (ie +'true' and +'false' can be 1 and 0). You can read more about it on MDN and you can read more about the differences between this and other ways to parse integers in js here.

Keri M.
  • 51
  • 5