0

So I have this piece of code:

if(item.name != "Banana" || "Apple"){
console.log("Good job");
} else{
console.log("Mad");
}

Basically, that part doesn't work != it still goes with those names. Doesn't ignore them.

4
  • if you have an array you need a loop Commented Apr 24, 2016 at 16:55
  • And where's the array? Also, it's if(item.name != "Banana" && item.name != "Apple"){ Commented Apr 24, 2016 at 16:56
  • I got loop, I just added part what doesn't work. Commented Apr 24, 2016 at 16:57
  • The || operator won't do what you think it will in that comparison. Commented Apr 24, 2016 at 16:57

2 Answers 2

4
var fruits = ["Banana", "Apple"];
if( fruits.indexOf(item.name) != -1 ){
    console.log("name is banana or apple")
} else {
    console.log("name is neither banana nor apple")
}

is this what you are looking for?

Anyway

if(item.name != "Banana" || "Apple")

this piece of code will always evaluate "Banana" over "Apple" as the or operator works with the first argument that is not falsy. "Banana" is evaluated as true then the if condition will always be

if (item.name != "Banana")
Sign up to request clarification or add additional context in comments.

Comments

0

Just to throw another option out there, you can filter an array through the use of higher order functions, in this case the builtin array's filter function:

var withoutApplesAndBanans = myArray.filter( function(item) { 
     return item.name !== 'Apple' && item.name !== 'Banana'; 
} );

You could also build an array of 'forbidden' words, and use that instead of a hard comparison:

var forbiddenWords = ['Apple, 'Banana'];

var withoutApplesAndBanans = myArray.filter( item => forbiddenWords.indexOf(item.name) === -1 ) ;

1 Comment

Wouldn't it be better then with var not = !array.some(function(x) {return x === item.name;});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.