Home > Back-end >  Why am I getting a number and not a concatenated string?
Why am I getting a number and not a concatenated string?

Time:09-20

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?

CodePudding user response:

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.

CodePudding user response:

'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.

  • Related