0

I am writing some codes for myself just to learn JS better and I was wondering if there is any difference in negation condition in if statement with an operator which compares two values or with operator which negates whole condition.

The first one is like this:

if(value != 'foo') {}

And the second one:

if(!value == 'foo') {}

Is any of them better, more appropriate?

Thanks!

Daniel
  • 13
  • 3
  • 1
    They are semantically differernt. The second one will always be `false` because `!value` is always a boolean thus won't be equal to `foo`. You probably meant to write `if (!(value == 'foo')` – derpirscher Aug 08 '21 at 20:54
  • 2
    `if(value != 'foo') {}` is same as `if(!(value == 'foo')) {}`. The first one is just more readable and preferred in 99% of cases. Your second example makes no sens, cause value will be the true in most cases. – ulou Aug 08 '21 at 21:03

2 Answers2

1

The first one,

if(value != 'foo') {}

is not only more readable, but is the only one that works how you seem to expect it to.

This means "value does not equal 'foo'".

Your second one,

if(!value == 'foo') {}

means "does the inverted truthiness of value equal 'foo'"

(it casts value into a boolean, and takes the negated version of that)

If, however, you meant to say

if (!(value == 'foo'))

for your second one, then the answer is still the same for which is better: the first one.

There's no reason to expand a statement, making it more confusing, when != already exists.


Look at this demo:

const value1 = "foo";
const value2 = "bar";

console.log("expected", false, true);
console.log("first option", value1 != 'foo', value2 != 'foo');
console.log("second option", !value1 == 'foo', !value2 == 'foo');
console.log("modifed second option", !(value1 == 'foo'), !(value2 == 'foo'));
test "foo" "bar"
expected false true
first option false true
second option false false
modifed second option false true

As you can see, your given second option will always result in false because it's testing if true (if value is empty string) or false (if value is non-empty string) is equal to the string literal foo

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
1

A basic explanation of this difference is that when you do value != 'foo' you are checking if value is not equal to 'foo', but when you do !value == 'foo' you are evaluating value as 'true' or 'false', then checking if that boolean evaluation is equal to 'foo'.

For example

let value = 'foo'

value == 'foo' //evaluates to true
value != 'foo' //evaluates to false
!value //evaluates to false
!value == 'foo' //also evaluates to false

Here is another post that talks about these operators https://stackoverflow.com/a/8616501/16600680