Let's see, let's go in parts:
In Javascript, as in many other interpreted languages, variables do not have type ; They have values , which is something else.
A variable is a totally neutral element : you can assign it the value you want. The type of the variable is determined, at all times, by the type of the value that it contains: if the variable does not exist or has no value assigned, then its type is undefined
, and, from there, it goes adopting the type of value that we assign: number
, string
, object
, ...
At any time, we can use typeof
to see the type of the value assigned to a variable.
Why it is not convenient to assign values of different types to the same variable is another issue: it can be considered an adaptation of the principle of sole responsibility : use a variable to one, and only one, function or responsibility.
This principle greatly reduces the number of errors in the code: if we call a variable, say, HoraDeInicio
, and decide that its value will be a Date
object with the start time of a certain operation, < strong> we should not use it to, for example, contain the string
with the text representation of that date / time.
Thus, at any point in our code where we see HoraDeInicio
, we know what it is and what it contains; whereas if we see StringHoraDeInicio
, we deduct quickly that it contains a string
with the text representation of the start time of something.
If you use the first one for both, not you can know at a glance the value it contains at any point in your code; you should look backwards , looking for the last assignment, to know the value it contains and if you can use it or not for a certain operation.