I want to directly answer your question of how the javascript interpreter knows the datatype of a variable.
The thing you need to know about javascript unlike, lets say, java is that a variable in JS doesn't hold the type. In JS it's the value that holds the type. And the value's type cannot be changed. But it can be coerced.
So even though a variable's value is intrinsicly a number, like the number 5, a new string "5" can be created from it through implicit coercion without you explicitly changing the variable's type because the variable itself never held the type to begin with.
It's not that the variable changes to a string, but rather a new string value will be created and used for the variable depending on the context of the expression you are using it in.
Look up javascript coercion for more info.