0

I just saw this construction for the first time in javascript

if (someConditionIsMet && !(anotherCondition && oneMoreCondition)) {
  return something
}

There is a !() inside of the if-conditional statement. I'm wondering what exactly that does. Is it just a way of grouping several conditions together and making sure they all evaluate a certain way before triggering logic? If so, is this merely to simplify the appearance or is there some logical advantage here?

2

3 Answers 3

4

Specifically for !(anotherCondition && oneMoreCondition), it means NOT (anotherCondition AND oneMoreCondition).

This is De Morgan's laws:

not (A and B) = not A or not B

Some might say that not A or not B is easier to read than not (A and B) but that's personal preference.

Expanding the whole condition using De Morgan's law would result in:

someConditionIsMet AND (NOT anotherCondition OR NOT oneMoreCondition)

in Javascript:

if (someConditionIsMet && (!anotherCondition || !oneMoreCondition))

You can use that expanded form if you think it's more readable.

Sign up to request clarification or add additional context in comments.

Comments

1

!() In any case in javascript means that if they are NOT true. So basically like in this case...

if(!(anotherCondition && oneMoreCondition)) {
Console.log("If both set to false this would run!");
}

if anotherCondition and oneMoreCondition were both set to false this would actually return true. This here might help you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT_!

Comments

0

It's evaluating the condition of anotherCondition && oneMoreCondition, and then reversing it.

So if the condition evaluates to true, the ! makes the condition evaluate to false.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.