assembler
assembler

Reputation: 3300

javascript parsing int values into int

I have an array of objects and there is the property id which may contains integers or strings. I'm using that property to compare, but now I'm guessing if it is more efficient to always convert that id in integer even if it is an integer or to ask if it is an string and then convert it. I mean this:

let myArray = [{id: 1, ...otherprops}, {id: 2, ...otherprops}, {id: '3', ...otherprops}, {id: '4', ...otherprops}];

Is this more efficient ...

for (let x of myArray) {
   if (parseInt(x.id, 10) === 3) {
      ...
   }
}

Or this code:

for (let x of myArray) {
   let id = -1;
   if (typeof x.id === 'string') {
      id = parseInt(x.id, 10);
   }
   if (id === 3) { ... }
}

Since the first code always convert I don't know if two conditions are better.

Upvotes: 1

Views: 52

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

If you know, that you have just numbers or stringed numbers, then you could take an unary plus + for conversion to a number, which does not change numbers.

var id = +x.id;

Upvotes: 3

Related Questions