Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toString or to parseInt javascript

So today I encountered this scenario. I had an integer and a string I needed to compare. In order to compare the two I would either have to toString() the integer, or parse the string to an int.

Here's my question, which one should I go for, is there any difference in performance for the two? (even if it is minimal) Is there a rule of thumb?

Here's a code example:

var intI = 1;
var stringS = '1';

if (intI.toString() == stringS)
console.log('are equal');

//Or
if (intI == parseInt(stringS))
console.log('are equal');

It would be best if I could declare the Integer as a string I know (as it is not used for calculations). But it is used everywhere on the site.

like image 325
Peter Rasmussen Avatar asked Dec 11 '22 19:12

Peter Rasmussen


2 Answers

It depends on the semantics you want more than performance. Should the string "001" be equal to the numeric value 1? If the answer is "yes", you should convert the values to numbers. If not, then you should compare as strings.

Don't worry about performance of such trivial things unless you've got an application that's doing millions of such operations.

Also note that parseInt() does not care whether a string of digits has trailing garbage at the end. That is

parseInt("123skidoo", 10) === 123

is true.

like image 78
Pointy Avatar answered Jan 03 '23 13:01

Pointy


is there any difference in performance for the two?

Not noticeable. However, there is a behavioral difference between the two methods, as parseInt would also convert strings such as 001 or 1xyz to the number 1. Do you want that? If not, you should toString the integer.

Btw, if you just use the == operator, the string will be ToNumbered implicitly. This does not allow strings that only begin with some digits (as 1xyz), but any number representation that is equivalent to 1 so for example 1.0 or 001.

like image 24
Bergi Avatar answered Jan 03 '23 15:01

Bergi