# Strong Typing Considerations

You could also call this one “Why I Hate JavaScript,” but there are many popular languages today that do not employ strong typing. JavaScript was just the language I happened to be working in when the following code had me pulling my hair out for nearly twenty minutes:

var value = \$("#myTextbox").val();
var calculation = value + (value * 0.05);


When I typed 1 into #myTextbox, I got an alert that said 10.05. I lost count of how many times I double checked my math.

Now, programmers who have been routinely working in JavaScript for some time might already have spotted the issue, but I’ve only recently spent a significant amount of time with the language. I’ve also completely given the answer away in the post title. The problem with my code was that jQuery’s val() method returns a string. My calculation variable was being assigned like this:

• Evaluate (value * 0.05), where value is implicitly cast as a number.
• Add value to the result of the above evaluation, where that result is cast as a string.

From what I’ve been able to gather after a little digging, the + operator will cast one operand as a string if the other operand is a string, regardless of their order. Similarly, the * operator will cast both operands as numbers all the time (I even tried this with boolean values).

## The Benefits of Strong Typing

Languages like JavaScript, Python, and Ruby let you do whatever you want with your variables, and that limits the ability for IDEs and compilers to perform static checking. My example is three lines of code and produces a fairly obvious logical bug, but it took me close to half an hour to identify the problem. When you have a system consisting of thousands or hundreds of thousands of lines of code, the risk of defects increases exponentially; most defects (logical bugs especially) are not nearly as obvious as my example. In a language with strongly typed variables, type conflicts can be caught at compile time instead of during testing or, worse, in production.