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

When are prompt values treated as strings and when aren't they?

var answer= prompt("What is 2 + 2?");
if (answer == 4) {
    alert("You are a bad ass!");}
else if (answer==3 || answer==5){
    alert("You are almost there!");}
else {
    alert("Just embarassing.");}

As we know prompts return strings, but even though I forgot to put quot. marks around 3, 4, and 5 in my code, the program works. So then I figured because it was a "numerical string", it returned a number, but that wasnt the case either. what is going on here?

3 Answers

Something called type coercion is happening here. The == operator attempts to convert operands to the same type if they're not the same type.

JavaScript also has a strict equality operator (===), also known as the identity operator, which checks for both value and type. If you try using it instead of == you'll see that the code will work differently.

Read more about it on the MDN.

The equality operator == does type conversions for you. So when comparing 3 and "3" the equality operator will attempt to convert them to a string, number or boolean to get a match.

If you wanted to enforce a numeric or string comparison from your prompt you could use the identity operator === where this conversion is not done and the types must also be the same to be considered equal.

thanks richard and dino!