As in every dynamic language, a JavaScript’s variable type is declared by its content (a variant). Types are still important because 4+5 isn’t like “4”+“5” or “4”+5. There are several ways to convert a String into a Number:

1
2
3
4
5
var fifteenString="15";

parseInt(fifteenString); // 15
Number(fifteenString); // 15
+fifteenString; // 15 (fastest)

Assuming you have an array of strings, which their content is a number:

1
var arr=[ "3", "5", "31", "71", "12" ];

and you want to cast all items to real numbers:

The Long Way

1
2
3
4
var result=[];
for (var i=0,l=arr.length;i<l;i++) result.push(+arr[i]); // or parseInt(arr[i]) or Number(arr[i])
result[3] // 71
typeof(result[3]) // "number"

A Shorter Way

Using JavaScript’s new native Array#map method, or any self-respecting JS Framework’s map function (MooTools’ Array.map, jQuery’s $.map), you can simply do:

1
2
3
4
5
var result=arr.map(Number);
result[3] // 71
typeof(result[3]) // "number"

// jQuery use: var result=$.map(arr,Number);

The arr.map(Number) simply runs over all items in array, executes the Number function on every item and adds the result into a new array. Just like as shown in the previous example.

On the same basis, you can convert to String, Date, RegExp. However, not a Boolean, since Boolean(“false”) is true.