1
var i1=3;
var i2="3";

var i3= i1+i2;
var i4= i2+i1;

So, i3 must be of type integer because of i1 and i4 must be of type string because of i2, but when I launch the code it turns out completely different. They are both equal to "33". How to sum them?

Michael Bianconi
  • 5,072
  • 1
  • 10
  • 25
Ivanko000
  • 21
  • 1
  • 1
    Does this answer your question? [JavaScript adding a string to a number](https://stackoverflow.com/questions/16522648/javascript-adding-a-string-to-a-number) – Michael Bianconi Jan 23 '20 at 19:49
  • _" i3 must be of type integer because of i1"_ - Why do you think so? If any of the operands in `op1 + op2` is a string the other operand will also be converted into a string. – Andreas Jan 23 '20 at 19:50

1 Answers1

1

Use Number() to parse values to number (integer/float)

var i1 = 3;
var i2 = "3";

var i3 = Number(i1) + Number(i2);
var i4 = Number(i2) + Number(i1);

console.log('i3', i3);

console.log('i4', i4);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60