> For the complete documentation index, see [llms.txt](https://cs.brash.ca/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cs.brash.ca/unit-3/conditionals/ifelse/logical-operators.md).

# Logical Operators

The [boolean logic](/unit-2/variables/booleans.md#boolean-logic) that we learned in [logic gates](/unit-1/binary-and-logic/logic-gates.md) can be applied to `if...else` statements. This is very important to be able to make decisions on more than one item at a time.

{% hint style="info" %}
If you have not seen the `&&` or `||` symbols, you should check out [Boolean Logic](/unit-2/variables/booleans.md#boolean-logic) and then come back to this page.
{% endhint %}

## NOT

The NOT operator, `!`, will reverse a boolean value (true becomes false and vice versa). It can be used in the middle of a statement for comparison with `!=` or `!==` but it can also be used outside a comparison like `!(5 < 10)`.&#x20;

### Examples

```javascript
if (someValue !== 0) {
    // Do something if the variable is not zero
}

if !(someValue > 10) {
    // Do something if the variable is not greater than 10
}

if !(someBoolean) {
    // Do something if the variable is false (because the ! makes it true)
}
```

## AND

Let's say you need to do something if a value is 10 *and* a boolean value is true... Typically you would need two if-statements:

```javascript
if (someValue == 10) {
    if (someBoolean) {
        console.log("Both are true");
    }
}
```

That code works, but it is gross and inefficient. We can combine those statements into one using the boolean logic AND operand `&&` (also called a *conjunction*):

```javascript
if (someValue == 10 && someBoolean) {
    console.log("Both are true");
}
```

Notice how much cleaner that looks? Not only is it easier to read, it will help your code in the long run (assuming your code becomes long and complicated).

### Example

```javascript
if (someValue > 0 && userInput == "Hello" && !someBoolean) {
    // Do something as long as all three of the  parameters equate to true
}
```

## OR

The `&&` operator will only equate to `true` as long as both (all) conditions are true. The logic of OR can be handy if you want something to work if one or the other or both is true. The operator for OR is `||`, also known as a *disjunction*.&#x20;

### Example

```javascript
if (someValue > 0 || someOtherValue == 2) {
    // This will run as long as at least one of the two conditions is true
}

if ((someBoolean) || someNumber === 0 || someString = "exit") {
    // Runs as long as one (or more) of the conditions is true
}
```

## Grouping

The three operators mentioned above can all be combined to form some amazing logic.\
**For example:**  `(A || C) && (!D || B) || !(C && B)`

### Order of Operations

Programming languages need to prioritize the order of the comparisons - the CPU cannot give more than one answer at a time (more than one comparison). Typically, languages will give the conjunctions `&&` higher priority. This can be problematic if you are not 100% sure of the order with which items are compared.

Thankfully, we can set the prioritizations with the use of brackets `()`. \
**For example:**  `A || B && C` will be evaluated as `A || (B && C)` due to automatic prioritization. We might want it to be evaluated as `(A || B) && C` and we will need to use the brackets to ensure this happens.

Writing out a truth table can help in deciding where brackets should go in your comparisons.

## Ternary Operator

{% hint style="info" %}
While not within the scope of our course, the ternary operator is a handy tool to learn.
{% endhint %}

Many programming languages have a shortcut for simple `if...else` statements. When your `if` statement consists of a simple check with a simple outcome for true and another simple outcome for false, you can utilize this shortcut. For Javascript it looks like this:

```javascript
condition ? trueExpression : falseExpression; 
```

If the `condition` can be evaluated to `true` (is [truthy](/unit-2/variables/booleans/truthiness.md#truthy)), then the first expression is evaluated. Otherwise, the second condition is evaluated. While it takes some getting used to, it can be a great way of coding something really quickly.

### Examples

In the example below, the prefix of "Ms." or "Mrs." depends on whether the person is married:

```javascript
let married = true;
let prefix = married ? "Mrs." : "Ms.";

console.log( `Hello, ${prefix} Brash` );
// Output:  Hello, Mrs. Brash
```

In this example, we will set a variable's value based on a person's age:

```javascript
let age = 16;
let license = (age > 18) ? "G" : "G1";

// license is set to "G1" in this case
```

The ternary operator can be *chained* to work similar to `if...else if...else` statements. More about this is [available via research](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator#Conditional_chains) as it goes well beyond the scope of this course.

## More Info

Don't like my description or details? Here's a fantastic overview:

{% embed url="<https://medium.freecodecamp.org/a-definitive-guide-to-conditional-logic-in-javascript-23fa234d2ca3>" %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://cs.brash.ca/unit-3/conditionals/ifelse/logical-operators.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
