Photo by Roman Skrypnyk on Unsplash
The shortest and best way to add two string numbers that you probably don't know
Hello Folks ๐
What's up friends, this is SnowBit here. I am a young passionate and self-taught developer and have an intention to become a successful developer.
Today, I am here with an amazing thing that you probably didn't know but now you will know about that. Happy reading
const x = "5"
const y = "4"
const z = x + y
This won't work, because adding string concatenates the string and therefore the output of the code will be "54"
and not 9
In this article, I will discuss two methods to add string numbers.
Using parseInt()
const x = "5"
const y = "4"
const z = parseInt(x) + parseInt(y)
Here, the string gets parsed to a number, therefore the output of this code must be 9
as both x
and y
variables are converted to a number.
If you use parseInt()
with words and letters it will return - NaN
and it stands for Not a Number.
This method was pretty simple to use, but now we go for a much simpler way.
Using the unary plus operator - Best method
As discussed above, we can't just add two string numbers with the +
operator. But there's a way to add two string numbers with the +
operator.
Let me show you,
const x = "5"
const y = "4"
const z = +x + +y
Using the +
operator alone before an element indicates a math operation and tries to convert the element to a number, and if it fails to do - it will return NaN
That is it for this article. I regularly share articles so make sure to click the follow button.
Thank you for reading, have a nice day! Your appreciation is my motivation ๐
- Follow me on Twitter - @codewithsnowbit
- Subscribe to me on YouTube - Code With SnowBit