When writing JavaScript I always took for granted that adding two integers together resulted in another integer. Or that adding two strings together would result in the concatenation. But I got to thinking, how does the language determine the types of instances behind the scenes prior to performing operations using those instances?
var one = 1;
var two = 2;
var fourStr = 'four';
var floaty = 1.5;
//this results in an integer
var three = one + two; //3
//but this results in a string
var result = fourStr + one; //'four1'
//and this results in a float
var floatenized = one + floaty; //2.5
Does the runtime just determine the instance types and then reference some sort of internal type precedence or something? Can anyone explain exactly how these operations are performed by the runtime when instances of differing types are combined?
The ecmascript specification describes exactly how operators like
+(section 11.6.1) act with different types.Relevant for your example:
+(number): result will be the sum of the floats+(number): result will be the concatenation of the string and the string represantation of the number+(string): result will be the concatenation of the string represantation of the number and the stringBut the
+can also act as a unary operator to transform a string into a number, as like as the binary-operator does (e.g.:+"4"+5==9,5-"4"==1).The type conversion algorithms are described in section 9 of the spec. How an environment should store the types of primitives and objects is not specified.