var x = “Hello”; // Assigning a string
var y = 12; // Assigning a number
var i = x + y;
console.log(i);
Now pause for a second and think about this snippet of code. What do you think will happen when we try to run this code? Will it break the code and produce an error message? Or will it try to output something in the console and fail there?
Give it a go and see what happens for yourself.
If you did go ahead and run the above code in your console to see what would happen, you were probably surprised by the result. JavaScript simply joins them together.
8.1
Remember earlier when I said JavaScript detects data types automatically? Well, this is an example of that in action. When we first declare our variables we assign the text ‘Hello’ to the variable x and the number 12 to the variable y. At this stage variable x contains a string, and variable y contains a number. Then the next line of code sees us attempt to add the variables together. The JavaScript engine sees this, and detects that it’s not possible to add a number to a bit of text, so the developer must want to join the variables together instead. In this case the number is not to be treated as a number, but rather another piece of text to join together with the ‘Hello’ variable. JavaScript then temporarily switches the data type over to a string and joins them together in the new variable. (Don’t worry, the initial variable x is still a number after this happens, though.)
Therefore, the output of the code is ‘Hello12’.
JavaScript simply evaluates the statement and decides the best way to handle the data types. The evaluation process happens from left to right, meaning as the JavaScript engine makes its way across the line of code, it is constantly evaluating how to handle the expression.
Let’s see some examples of how this happens.
Open up Google Chrome and head over to the developer console again. Click the console tab and check out what happens when you enter these statements: