0

I have array, by which at some point am mapping the array and calculating sum and percentages. So while implementing the logic i saw that, when i use '*' directly its working but when i use '+' it just adds the two string

For example:

const a = '100';
const b = '10';

const c = a * b;

const d = a + b;

console.log(d)

When i checked the d , it gives '10010' and when c it gives '1000' ! How is this ?

But when i use parseInt(a) + parseInt(b) it works perfectly with 110 as output

  • 2
    `a` and `b` are strings, so `+` is string contenation, and `*` is not defined so JS will try to convert `a` and `b` into something for which `*` _is_ defined. If you want `a` and `b` to actually _be_ numbers then yes, you're going to have to convert them first, but I'd recommend using `parseFloat`, not `parseInt`. Only use `parseInt` if you're not dealing with strings that don't represent decimal values (like binary, octal, base-52, etc), or you're explicitly writing code to throw away the factional part of a number-as-string. – Mike 'Pomax' Kamermans Dec 25 '20 at 17:21
  • So if we use ```*``` js will automatically convert that into numbers ? – Christina122 Dec 25 '20 at 17:24
  • @Christina122 yes if you use * it will be treated as numbers. you cant multiply strings. – Re9iNee Dec 25 '20 at 17:26
  • It will _derive_ numbers, not strictly speaking convert them, and only for the purpose of evaluating that `*`. – Mike 'Pomax' Kamermans Dec 25 '20 at 17:27
  • You can try this ` +a * +b`, this will coerce them into numbers. – Robert Dec 25 '20 at 17:28
  • `+a + +b` *edit – Robert Dec 25 '20 at 17:34

1 Answers1

0

In JavaScript there are no primitive datatypes like int, float etc. There are only variables which can be initialized with everything you need. For your example

const a = 100;
const b = 10;

const c = a * b;

const d = a + b;

console.log(d);

should work perfectly, because I removed ''. With '' the constant thinks it is a string provided. Without '' there are just the numbers saved in the constants. Also + doesn't work in your example, because as I said the constants think the numbers are a string due to ''. So it just puts this two "strings" together and not summing them up.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jannik Schmidtke
  • 1,257
  • 2
  • 5
  • 15
  • Except that's no longer true, there is a primitive pure integer datatype that uses the `n` suffix, which gives you a [BigInt](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/BigInt) rather than a [Number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number) – Mike 'Pomax' Kamermans Dec 25 '20 at 17:27
  • I understand, but in my case i need to keep those as strings ! – Christina122 Dec 25 '20 at 17:33
  • Oh okay sorry, @Christina122. Then to answer your question quick and simple: you don't need parseInt() when multiplying two strings. – Jannik Schmidtke Dec 25 '20 at 17:37