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

Can some explain to me why my numbers are getting added like strings and not numbers? Am I using parseInt incorrectly?

I created a variable named firstScore and then defined it using a prompt, I then immediately converted the prompt string to a number using parseInt. I did the same for secondScore, then added them in a new variable named totalScore. When I add firstScore and secondScore it gets read like a string, however if I add a variable with a number for exmaple like firstScore + 100, it gets read like a number. I'm confused do I need to manually convert every string number individually with parseInt to get it to work consistently? The top program works correctly and the bottom one doesn't, help would be greatly appreciated.

console.log("start program");
var age= prompt("how old are you?");
age=parseInt(age);
var score=100;
alert(age+score);
console.log("program ended");

console.log("start program");
var firstScore= prompt("what was your first score");
fisrtScore= parseInt(firstScore);
var secondScore= prompt("what was your second score");
secondScore= parseInt(secondScore);
var totalScore= secondScore + firstScore;
alert("your total score is " + totalScore + "!");
console.log("program ended");

Hey Brandon, can you re-post the code using markdown? It says how to do it if you go to the bottom of the page were you answer then there is a link for the cheatsheet.

Never mind, posted the comment and when the page refreshed you had already done it :) .

1 Answer

Julian Gutierrez
Julian Gutierrez
19,325 Points

It seems you have a typo in your second example. On the third line you have fisrtScore instead of firstScore. When using prompt the return type is a string so it would be wise to convert any numbers to integers like you have done. You can actually do it on one line.

var firstScore = parseInt(prompt('what was your first score'));

Thank you! that really helps.