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) Making Decisions with Conditional Statements The Conditional Challenge

Michael Lockrey
Michael Lockrey
2,762 Points

Not sure why my OR conditional didn't work as expected

I encountered this issue in the Simple Quiz project in Javascript Basics course.

This was the code I used for my second quiz question but for some reason it would always be counted as correct - even when I entered something other than Sydney or Australia.

Code extract

var answer2 = prompt("Where was Michael born?");
if (answer2 === 'Sydney' || 'Australia') {
 correctAnswers += 1; 
 console.log(correctAnswers);  
}

Debugging steps undertaken

I set up the console log to print out the variable correctAnswers during each answer loop and this confirmed that it was happening with this question.

Then I changed the IF conditional line to: `if (answer2 === 'Sydney' || answer2 === 'Australia') {'

And that seemed to fix things but I'm still clueless on why I receiving a correct mark for any "string" I entered.

1 Answer

Because the second half of your OR conditional you're passing in a string and strings are evaluated as true, so even though the first section is false the second half will always be true.

Example:

var one = 1;

// these are both true

if ("one"){
alert("yay");
} 


if (one === 1){
alert("yay");
} 
Michael Lockrey
Michael Lockrey
2,762 Points

Thanks so much David Tonge

I will have to remember that strings are always "truthy" values! And I should have been more careful with using an OR conditional.

Cheers!

no prob