Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript: If String Is Not A or B Then

How do I achieve this with a single if ? In other words, if(fruit != "apple" || fruit != "orange"){ is not producing the expected result?

fruits.forEach(function(fruit){
  if(fruit != "apple"){ // < ----I want to use a compound OR, or compare multiple strings.
    if(fruit != "orange"){ // <---------I want this nested if gone.
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});
const fruits = ["apple","orange","banana","cherry"];

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    console.log(fruit + " is not apple");
  }
});

fruits.forEach(function(fruit){ //<------- this is what I'm having problems with
  if(fruit != "apple" || fruit != "orange"){
    console.log(fruit + " is not apple or orange [one]");
  }
});

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    if(fruit != "orange"){
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Pointy points out that:

const fruits = ["apple","orange","banana","cherry"];

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    console.log(fruit + " is not apple");
  }
});

fruits.forEach(function(fruit){ //<------- this is what I'm having problems with
  if(fruit != "apple" && fruit != "orange"){ // notice
    console.log(fruit + " is not apple or orange [one]");
  }
});

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    if(fruit != "orange"){
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading