🖥️
Intro to Computer Science (ICS3U/C)
  • An Introduction to Computer Science
  • Videos & Slides
  • Unit 1: In the Beginning
    • The History of Computers
    • Binary & Logic
      • Bits and Bytes (Binary)
      • Transistors (Changing Bits)
      • Logic Gates
        • Poster
        • Logic.ly
    • The Parts of a Computer
  • Unit 2: Intro to Code
    • How Do We Code?
      • Coding Conventions (Rules)
      • Commenting Code
    • What is HTML?
      • Hello World! (in HTML)
      • HTML Slideshow
    • Hello World!
    • Input / Output
      • The Console
      • Prompt, Alert, Confirm
    • Variables & Data
      • Strings (Text)
      • Numbers (Values)
        • Converting & Rounding
        • The Math Object
          • Random Numbers
      • Booleans
        • Truthiness
      • Arrays
  • Unit 3: Control Flow
    • Conditionals (if this, do that)
      • If...Else
        • Logical Operators
      • Switch / Case
      • Ternary Operators
    • Loops (Repeating Code)
      • For...Loop
      • While & Do/While Loops
    • Debugging
  • Unit 4: Functions
    • Functional Programming
    • User Defined Functions
      • Hoisting and Scope
    • Calling a JS Function
  • TL;DR
    • Programming Basics
    • Slideshows & Demos
    • Javascript Syntax Poster
  • Advanced Topics
    • Recursion
    • Structures & Algorithms
    • Mmm... Pi
  • External Links
    • Typing Club!
    • repl.it
    • Khan Academy
    • Geek Reading
    • ECOO CS Contest
Powered by GitBook
On this page
  • NOT
  • Examples
  • AND
  • Example
  • OR
  • Example
  • Grouping
  • Order of Operations
  • Ternary Operator
  • Examples
  • More Info
  1. Unit 3: Control Flow
  2. Conditionals (if this, do that)
  3. If...Else

Logical Operators

Using boolean logic inside if statements.

PreviousIf...ElseNextSwitch / Case

Last updated 6 years ago

The that we learned in 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.

If you have not seen the && or || symbols, you should check out and then come back to this page.

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).

Examples

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:

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):

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

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.

Example

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

While not within the scope of our course, the ternary operator is a handy tool to learn.

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:

condition ? trueExpression : falseExpression; 

Examples

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

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:

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

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

More Info

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

If the condition can be evaluated to true (is ), 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.

The ternary operator can be chained to work similar to if...else if...else statements. More about this is as it goes well beyond the scope of this course.

available via research
logic gates
LogoA definitive guide to conditional logic in JavaScriptfreeCodeCamp.org
truthy
boolean logic
Boolean Logic