How to convert a string to a number (integer) in JavaScript: best ways
Hello everyone! I just started learning JavaScript and ran into a problem. I need to get a number from a string, for example, from an input form where the user enters their age. I tried just adding two strings, but it results in concatenation, not addition.
Here's an example of my code:
```javascript
let age1 = "25";
let age2 = "30";
let sum = age1 + age2; // Results in "2530", not 55
console.log(sum);
```
I understand that strings need to be converted to numbers, but I don't know how to do it correctly. I've seen many different methods online: parseInt(), Number(), unary plus (+), but which one is better? And what's the difference? I've also heard there are pitfalls, for example, when the string contains not only digits. Please advise how to reliably and safely convert a string to an integer.
No answers yet.
Log in to leave an answer
Blogs