6
Recently I had seen on the website of MDN Web Docs that it was possible to convert a String
in a Number
even in the example below:
let n1 = "10";
console.log(typeof n1); //=> string ("10")
The variable n1
holds the value "10"
, who’s kind string
. But if you try to do this:
let n1 = "10";
console.log(typeof +n1) //=> number (10)
The variable n1
becomes a value of the type number
. The problem is that if instead of displaying the variable type n1
, and show the conversion, the variable is no longer number
, and yes string
:
let n1 = "10";
console.log(n1 + 10 + " " + typeof n1); // "1010" (string)
console.log(+n1 + 10 + " " + typeof n1) // "20" (tipo string)
How is this possible? In the last example it returns the type string
, then it was to concatenate +n1 + 10
and give the same result as the first example that is 1010
, but not it adds up the two values and gives the result 20
, but it does not behave as a value of type number
is a value of the kind string
.
Can someone please explain to me if this is a bug or if I don’t understand something right? I know there are other ways to turn something into certain things but I want to focus on that problem.
On these tests of yours at the end of the question, note that the operations are evaluated from left to right. Then the first case starts with string + number, and the second with number + number.
– bfavaretto
Not directly related, but in some cases, use
+
to convert string to number can give different results fromparseInt
andparseFloat
(which are the functions I prefer to use instead of+
). See more details at https://answall.com/a/410229/112052– hkotsubo