The + Operator in the Happy Land of JavaScript

I've been learning JavaScript over the last few years, but you only find all of the pits within a language over time.  So recently, a colleague stepped into the office to inform the rest of us that in JavaScript, the expression var x = "5" + 2 will result in x = "52", a string, but var x = "5" - 0 will result in x = 5, a number!  The former is something that I was already pretty clear on. However, I had not thought through all the implications of operator use and precedence. So, I began to play around and do some review, and he is surely correct. As you may know, JavaScript very helpfully and very dangerously will change data types of your vars for you, and it will do so within expressions. Essentially, for primitive types, it destroys the var and recreates it again with the new value and the matching type you’ve assigned it. This is very important to know when using the mathematical operators, particularly the + operator. And here's why: the + is two-timing operator being used for both mathematical addition and string concatenation, and danger surely layeth ahead.

Basically, IF a string containing only number characters (e.g. "502") is present in an expression using + then the JS compiler will assume you are wanting to concatenate rather than perform addition, and it will attempt to convert the other numbers in the expression to strings, perform the concatenation, and the outcome will be a string!

However, for any other mathematical operator, the JS compiler will assume you want to do math, so the JS compiler will attempt to convert the string to a number,  perform the mathematical operation, and the outcome will be a number!

Precedence of operators applies, so again be careful, and precedence is precisely the point. When an expression involves a stringed number, i.e. "52", and the + operator, then the precedence is concatenation before other mathematical operations, and that expression will return a string, and you have to keep working out the precedence from there with the same rules applying. Obviously, once the string is converted to a number then from there on, it will remain a number, and mathematical operations are assumed. And also, if you've got a single string in a series of nested expressions all using the + operator, then your result will be a string.

Some sampling of the weirdness: var x = “5” + 2; // x = "52", a string! var x = “6” - 2; // x = 4, a number! var x = “3” * 2; // x = 6, a number! var x = (“2” / 1) + 2; // x = 4, a number! var x = (“5”+1) + 2*4; // x = "518", a string! var x =(“5”+1) * 2*4; // x = 208, a number! var x =((("5" + 1) + 2) + 39); // x = "51239", a string!

In the free and happy land of JavaScript where a variable can be whatever it wants to be and the + operator pulls double duty, walk circumspectly and fall ye not into thither pit!

Chadamoore.com · Copyright © · Caveat Lector