Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.