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

Shawn Manning
Shawn Manning
2,775 Points

OR (||) operator not working as expected. Please help.

On my second question variable, I decided to use the or (||) operator, for multiple correct answers. Problem is, it is returning the user input as correct no matter what the input is.

Here is the code:

var q2 = prompt('What is better, A or B?'); if ( q2.toUpperCase() === 'A' || 'B') { alert('That was correct. Next question.'); score += 1; } else { alert('That was incorrect. Next question'); }

I can enter any character and it will output the 'if' alert of "That was correct. Next question."

I'm stumped!

2 Answers

Kelly von Borstel
Kelly von Borstel
28,880 Points

Hi, Shawn. This is a common error! You need to have the full equality test on both sides of the || operator.

q2.toUpperCase() === 'A' || q2.toUpperCase() === 'B'
shadryck
shadryck
12,151 Points

kellyvonborstel2 is completely right, just to clarify a bit more.

With q2.toUpperCase() === 'A' || 'B' you test if the string 'B' is true. Which will always return true since strings which are not empty always equal true.

'' // false
'0' // true
'abc' // true
'false' // true

It's also the same as

if('B') {
}

Both sides of the OR operator will check their own statement.

Shawn Manning
Shawn Manning
2,775 Points

Awesome thank you for explaining why and what happens with my initial attempt. Broadens my understanding of how javascript works.