-2
if(openmenu != para){
addClass(openmenu , 'collapsed');
}

I am a beginner of JS, I want to add a classname to a element after a if statement. However, if(openmenu != para) and if(!openmenu == para) showed completely different result. Does anyone know why?

  • 3
    [Equality comparisons and sameness - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) – Andreas Mar 17 '22 at 10:47
  • 2
    It depends on what the values of `openmenu` and `para` are. That's fundamental information to include in the question. **If** they were both booleans, those two comparisons would have the same result. So clearly, they're not both booleans. – T.J. Crowder Mar 17 '22 at 10:48
  • See [What does this symbol mean in JavaScript?](/q/9549780/4642212) and the documentation on MDN about [expressions and operators](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators) and [statements](//developer.mozilla.org/docs/Web/JavaScript/Reference/Statements). Duplicate targets found by searching [`[js] code:"!x === y"`](/search?q=%5Bjs%5D+code%3A%22%21x+%3D%3D%3D+y%22) and [`site:stackoverflow.com js "!=="`](//google.com/search?q=site:stackoverflow.com+js+%22%3D%3D!%22). – Sebastian Simon Mar 17 '22 at 11:10

4 Answers4

1

!openmenu == para is parsed as (!openmenu) == para, so it first negates openmenu and then checks whether it is equal to para, which is most likely not what you want to do. You could write !(openmenu == para) which would mean the same thing as openmenu != para.

Guillaume Brunerie
  • 4,676
  • 3
  • 24
  • 32
0

!a == b inverts a's value. For example if it's true, using ! will invert it to false.

if(!true == false) equals to if(false == false) which results as true.

but if(a != b) compares values, lets say a is true and b is false, so if(true == false) => false values are not the same. :)

Ali Demirci
  • 5,302
  • 7
  • 39
  • 66
0

In this case, if a==null and b==false so !a = true.

Then !a == b is false but a!=b is true. I hope that answer is helpful to you.

0

You are comparing different values. When you add ! in front it toggles the value between true and false

const openmenu = 1;
const para = 2;

console.log(!openmenu) // toggles to false
console.log(!para) // toggles to false
console.log(!openmenu == para) // false == 2
console.log(openmenu != para) // 1 != 2

console.log(!"Turtle") // converts to false
semperlabs
  • 458
  • 4
  • 7