10 + 3= 103??
So in basic math 10 + 10 = 20; well in javascript sometimes this is not the case. There are many times when working with JS that 10 + 10 will equal 1010. What gives? Since “strings” are a very common data type used on the internet a lot of times when using JS a number will actually be a string. So instead of seeing 10 + 10 what you are really telling the computer to do is actually “10” + 10. Since there is a string involved in the command JS will automatically return a string. Just as …
"hello" + "world"
Will return
"helloworld"
If you add
"hello" + 100
You will get
"hello100"
This can get pretty annoying an a little confusing but all is not lost thanks the the parseInt() function! What parseInt() does is turn an string into an integer, which solves our pesky problem!
So…
parseInt("10") + 3
Will finally return what we want
13
If you are running into this silly but all too common problem one of your numbers is most likely a string. Its always good practice to check the data type as well to avoid these issues. Its pretty simple to do using the typeof() operator.
console.log(typeof "10")
will log to the console
string
and
console.log(typeof 10)
will log
number
The typeof operator works with all JS data types, so its a great tool. I use this a lot when writing JS code just to make sure I know what data types I am dealing with. There are some quirks that make JS a little tricky to use sometimes, but fortunately there are always ways to get around them. I hope this entry helped!