Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

parseInt vs. +

Is there any meaningful difference between the two different ways this string is converted to an integer?

var ratingInput = '3';

var newRating = parseInt(ratingInput);

OR

var newRating = +ratingInput;

1 Answer

In that particular context there is no difference. If you were to apply the same code to a different string though, the results could be different. For instance

var ratingInput = '3.5';
var newRating = parseInt(ratingInput); // => 3
var newRating2 = +ratingInput; //  => 3.5

or

var ratingInput = '3 stars';
var newRating = parseInt(ratingInput); // => 3
var newRating2 = +ratingInput; //  => NaN