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

Condition broken when using the or || operator

i want to print out to the screen the "r" and "s" character from the text string, but i'm getting the entire string printed.

here is the code:

var someText = "find it find it find it find it r find it find it find it find it steet";

for(i = 0; i<someText.length; i++) {
     if (someText[i]=="r" || "s") {
    document.write(someText[i]);
}

}

with else if it works, but i want to know why i can't use the || operator.

 var someText = "find it find it find it find it r find it find it find it find it steet";

          for (i = 0; i < someText.length; i++) {
              if (someText[i] == "r") {
                  document.write(someText[i] + " ");
              } else if (someText[i] == "s") {
                  document.write(someText[i]);
              }

          }

3 Answers

Mike Bronner
Mike Bronner
16,395 Points

The "||" operator doesn't work the way you are thinking (choose between two values), instead it works to test between multiple statement for true or false:

if ((myValue == 5)
    || (myWord == "gotcha")
{
    //then do this
}
else
{
    //do that
}
Stone Preston
Stone Preston
42,016 Points

try

if (someText[i]=="r" || someText[i] == "s")

Thank you Mike Bronner / Stone Preston, now it works.