When to use parseInt

javascript, jquery, parseint

Solution

The `.text()` method will always return a string. Some operators, like the `+` operator, are overloaded to perform both arithmetic and string operations. In the case of strings, it performs concatenation, hence the "51" result.

If you have a string and need to use a non-coercing operator, you will have to use `parseInt` (or some other method of converting to a number).

However, the `*` operator for example implicity performs this coercion, so you wouldn't need the `parseInt` call in that situation (see an updated fiddle for example).

Note that the increment `++` operator does coerce its operand, but you've used the postfix operator so it won't have any effect. Use the prefix operator and you can see it working:

$('#withoutParseIntButIncrement').text(++value);

So, to summarise:

// Parses string to number and adds 1
$('#withParseInt').text(parseInt(value) + 1);

// Coerces number 1 to string "1" and concatenates
$('#withoutParseInt').text(value + 1);

// Implicity coerces string to number, but after it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(value++);

// Implicity coerces string to number, before it's been inserted into the DOM
$('#withoutParseIntButIncrement').text(++value);

// Implicity coerces to number
$('#withoutParseIntButMultiply').text(value * 2);

Side note: it's considered good practice to always pass the second argument (the radix) to `parseInt`. This ensures the number is parsed in the correct base:

parseInt(value, 10); // For base 10

Problem

Which rule do I have to follow when extracting numbers out of DOM and calcluation with them? How does javascript knows that a value is a number or not? Should I always use parseInt? Given following Code: HTML ``` <div id="myvalue">5</div> <div id="withParseInt"></div> <div id="withoutParseInt"></div> <div id="withoutParseIntButIncrement"></div> ``` JS & jQuery: ``` var value = $('#myvalue').text(); $('#withParseInt').text(parseInt(value) + 1); $('#withoutParseInt').text(value + 1); $('#withoutParseIntButIncrement').text(value++); ``` Gives following output: ``` 5 6 51 5 ``` Fiddle: http://jsfiddle.net/ytxKU/3/

Original source

Related problems