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 JavaScript Basics (Retired) Working With Numbers Numbers and Strings

Richard Hummel
PLUS
Richard Hummel
Courses Plus Student 5,677 Points

parseInt not giving me correct value

I'm not sure what I'm doing wrong in my syntax in the app.js file.

app.js
var width = '190px';
var numOfDivs = 10;
parseInt(width);
var totalWidth = width * numOfDivs; 
index.html
<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JavaScript Basics</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>

1 Answer

Michael Davidson
Michael Davidson
5,519 Points

Okay so what you've done looks like it makes sense, but there is a problem.

Your javascript:

var width = '190px';
var numOfDivs = 10;
parseInt(width);
var totalWidth = width * numOfDivs; 

While you did parseInt(width) in there, you never set width = parseInt(width) so it doesn't change your variable. So your final call takes the string '190px' and says NAN

If you do

var width = '190px';
document.write(width + ' <br>');
width = parseInt(width)
var numOfDivs = 10;
document.write(width + ' <br>');
var totalWidth = width * numOfDivs; 
document.write(totalWidth);

Your document will output

190px 190 1900

Because when you change the variable to the parse int, you assign that as what you're working with :)

[Mod Note - Changed to answer instead of comment so this can be voted on or marked as best answer.]

Richard Hummel
Richard Hummel
Courses Plus Student 5,677 Points

OK so I'm essentially reassigning the 'width' variable to the value of the parseInt. Thanks.