4umi.com/web/javascript/type

Varying variable types

Timing Javascript

Of all the different types of variables, String and Number objects seem to be the most common ones. Numbers are just numbers, although not all numbers are the same. Strings however can be numbers, too. That is why '1' + '1' = '11' and 1 + 1 = 2 and many other oddities are actually not that odd at all. The plus sign is used for gluing strings together, and also for adding numbers up, two very distinct actions but sometime hard to distuingish, as they have the same syntax and may occur in the same places or even the same statements.

Because when the plus finds values of different types, say a number and a string, automatic type conversion kicks in and the result is a string.

Optimization

A small test is undertaken to determine the most efficient way of doing the conversion by repeating a small task a large but finite number of times in two slightly different ways and compare the times it takes for each of them. The outcome is likely to vary widely accross machines, due to differences between operating systems as well as browsers, but it appears that generally parseInt bites the dust against the quick little +. Adjust the amount of repetitions in the test to suit your system.

Iteration

Click a line to run it.

var d, i, j, r = window.document.forms.f.elements.r;

d = new Date(); i = r.value; while( i-- ) { j = '' + i; convertplus( i ); } report( d );/**/
d = new Date(); i = r.value; while( i-- ) { j = '' + i; convertpint( i ); } report( d );/**/
d = new Date(); i = r.value; while( i-- ) { j = '' + i; convertplus( j ); } report( d );/**/
d = new Date(); i = r.value; while( i-- ) { j = '' + i; convertpint( j ); } report( d );/**/

function convertplus( n ) { return +n; }
function convertpint( n ) { return parseInt( n, 10 ); }

function report( d ) { window.alert( new Date() - d + ' ms.' ); }

The last line is an example of mathematical calculations on numbers and type conversion to a string all in one statement.