1

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.

1

2 Answers 2

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_()

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

Comments

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.

Comments

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.