0

I have this code

var n = parseInt(prompt("Give me a number"));
var sum = 0;
for (let i=0; i < n.toString().length; i++){
    let expon = n.toString()[i] ** n.toString().length;
    sum += expon;
}

My doubt is the following: If my n is 371, n.toString()[0] is '3' (A STRING!!), why is it then that when I do ** n.toString().length (which is 3). I get 27 ?!!?

Also, it is clear to me that if x = '3' and I do x + x I get '33' and not 6. Can this happen to the addition only? why?

  • 4
    The (+) is the operator for addition and concatenation of string in JS. But the other numeric operators are only for numbers. If they find a string they will convert it into a number. – Xion 14 Sep 19 '22 at 21:54
  • 2
    3 to the power of 3 is 27. – Andy Sep 19 '22 at 21:54
  • 3^3=27? Works correctly afaik. – Flame Sep 19 '22 at 21:57
  • Relevant: [Why does JavaScript handle the plus and minus operators between strings and numbers differently?](https://stackoverflow.com/q/24383788) – VLAZ Sep 19 '22 at 22:10

2 Answers2

0

Check this: https://medium.com/swlh/strings-and-basic-mathematical-operators-in-javascript-e9de3d483dae

In simple words - in JavaScript, when trying to add String type to non-String type, adding operator automatically casts added elementsto both be set of characters, because '+' can be understood as adding OR as concatenating. Although, every different arithmetic operations (substracting, dividing, multiplying, powering, etc.) performed on String and non-String type will force the first one to be casted to the Number form. If not possible, we will receive NaN result.

maslosh
  • 111
  • 4
0

'3' ** 3 is 27 because ** converts both its arguments to numbers if possible. It has no function other than numeric exponentiation.

'3' + 3 is '33' because + has multiple possible functions (addition and string concatenation), and if at least one of the arguments is a string, string concatenation is used instead of addition. In another universe, it may well attempt to do numeric addition first and end up at 6, but the language designers of our universe chose to do it this way round.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119