JavaScript typing

As we saw in Chapter 1, TypeScript - Tools and Framework Options, JavaScript objects and variables can be changed or reassigned on the fly. As an example of this, consider the following JavaScript code:

function doCalculation(a,b,c) { 
    return (a * b) + c; 
} 
var result = doCalculation(2,3,1); 
console.log('doCalculation():' + result); 

Here, we have a doCalculation function that is computing the product of the arguments a and b, and then adding the value of c. We are then calling the doCalculation function with the arguments 2, 3, and 1, and logging the result to the console. The output of this sample would be as follows:

doCalculation():7

This is the expected result as 2 * 3 = 6, and 6 + 1 = 7. Now, let's take a look at what happens if we inadvertently call the function with strings instead of numbers:

result = doCalculation("2","3","1"); 
console.log('doCalculation():' + result); 

The output of this code sample is as follows:

doCalculation():61

The result of 61 is very different from our expected result of 7. So what is going on here?

If we take a closer look at the code in the doCalculation function, we start to understand what JavaScript is doing with our variables and their types.

The product of two numbers, that is, (a * b), returns a numeric value; so JavaScript is automatically converting the 2 and 3 values to numbers in order to compute the product and is correctly computing the 6 value. This is a particular rule that JavaScript applies when it needs to convert strings to numbers, and comes into play when the result of a calculation should be a number. The addition symbol, (+), however, can be used with numbers as well as strings. Because the argument c is a string, JavaScript is converting the 6 value into a string in order to add two strings. This results in the 6 string being added to the 1 string, which results in the 61 value.

This code snippet is an example of how JavaScript can modify the type of a variable based on how it is used. This means that to effectively work with JavaScript, we need to be aware of this sort of type conversion, and understand when and where this conversion could take place. Obviously, these sorts of automatic type conversions can cause unwanted behavior in our code.