What is a Variable Type?
In computer programming, the type of a variable determines what values a variable can hold and what can be done with the variable. As an example, numeric variables can have mathematical operations performed on them, whereas string variables cannot (more on this later).
Different programming languages support different types of variables, but generally, they fall into the categories of numeric, string, and object variables.
Strongly Typed Languages
Strongly typed languages enforce the correct usage of variable types and will emit warnings and errors if you try to perform an action on a variable type that does not support that action.
Loosely Typed Languages
On the other hand, loosely typed languages will ignore these incompatibilities and try and continue with a best-case scenario – coercing variables of the wrong type to a type that can be used for the unsupported action.
This may seem convenient but often results in unexpected behavior. Relying on your computer to correctly guess what type a variable was meant to be is unwise. When programming, your intentions should be clear and unambiguous – both so that your computer – and future programmers who might work on your code – know what it is supposed to be doing.
Here’s an example:
Adding two numeric values works as you would expect:
3 + 3
What if the values being added are strings that contain a number?
'3' + '3'
Returns the two strings joined – the numbers are not treated as numbers but simply as characters in the string:
Subtracting numbers also works as you would expect:
3 + 3 - 3
Subtracting a string containing a number, however:
'3' + '3' - '3'
Seems to make no sense at all!
In a complex application, these issues can pile up quickly. Making sure your variables contain the right type of value is important if you want a reliable, accurate application