Start learning free

LESSON 84 OF 348 · CONDITIONAL STATEMENTS

Not Operator in TypeScript: Inverting Conditions with !

Lesson Read the full explanation

The logical not operator (!) is used to invert the value of a boolean condition. For example:

7 <= 10 // Evaluates to true
!(7 <= 10) // Evaluates to false

12 != 12 // Evaluates to false
!(12 != 12) // Evaluates to true

!true // Evaluates to false

It is oftenly used with boolean variables:

let hungry = true;
if(!hungry) {
    console.log("I can wait a little longer");
}
else {
    console.log("I need food!");
}

!hungry evaluates to false, so we enter the else and print "I need food!".

Assignment
Follow the Coding Tutorial and play with the not operator.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS

    Not Operator in TypeScript, explained

    What the not operator does

    The logical not operator ! inverts a boolean: true becomes false and false becomes true. It takes one operand, written after the operator, unlike && and ||, which take two.

    7 <= 10        // true
    !(7 <= 10)     // false
    
    12 != 12       // false
    !(12 != 12)    // true
    
    !true          // false
    

    When you negate a whole comparison, the parentheses matter. ! binds tighter than comparison operators, so !(7 <= 10) negates the result of the comparison, while !7 <= 10 would negate the number 7 first. The second form gives false and then compares that with 10. The compiler reports an error for it, and the JavaScript runs and produces true, which is not what the first form means.

    Using it with boolean variables

    The operator is most natural with variables that already hold a boolean:

    let hungry = true;
    if (!hungry) {
        console.log("I can wait a little longer");
    } else {
        console.log("I need food!");
    }
    

    Here !hungry is false, so the if block is skipped and the else block prints I need food!. Read !hungry as "not hungry". A name like isSunny that reads as a statement works well with it: !isSunny is "it is not sunny".

    TypeScript details

    • ! works on any value. It first decides whether the value counts as true or false and then inverts that. The values that count as false are false, 0, "" (an empty string), null, undefined and NaN. Everything else, including "0", counts as true:
      console.log(!0, !"", !"text", !NaN);
      
      true true false true
      
    • Double negation. !!value converts any value to a real boolean: !!"text" is true and !!NaN is false. With a boolean variable it does nothing, so there is no reason to write it.
    • != is a different operator. a != b compares two values, while !a inverts one. Prefer !== for "not equal", since it never converts types.
    • The non-null assertion x!. When ! follows an expression, TypeScript reads it as a type-level hint that the value is not null or undefined. It is erased when compiled and has nothing to do with the logical not, which comes before its operand.

    The exercise

    The code has a variable isSunny. The program must print "Learning to code" when it is not sunny, and "Going to the beach" otherwise.

    1. Write an if whose condition is !isSunny, true when the variable holds false.
    2. Log "Learning to code" in that block.
    3. Add the else block, on the same line as the brace that closes the if. It runs when !isSunny is false, which means isSunny is true, and logs "Going to the beach".
    let isSunny: boolean = true;
    
    if (!isSunny) {
        console.log("Learning to code");
    } else {
        console.log("Going to the beach");
    }
    

    With isSunny set to true, !isSunny is false, so the program prints:

    Going to the beach
    

    Set isSunny to false in the editor above and the message changes to Learning to code.

    Style: avoid negations that need a second thought

    This exercise puts the negative case first on purpose, so you can practise !. In ordinary code, an if (!x) { A } else { B } is easier to read as if (x) { B } else { A }. Reserve ! for the places where it makes the condition shorter or clearer, such as if (!isValid) return; as an early exit.

    Combining it with and and or

    The operator can be applied to a combined condition too. !(a && b) is true unless both are true, which is the same as !a || !b. In the same way, !(a || b) is the same as !a && !b. Rewriting a negated condition this way is often the simplest route to a readable one.

    Common mistakes

    • Forgetting the parentheses around a comparison. !x > 5 negates x first. Write !(x > 5), or better, x <= 5.
    • Negating twice by accident. !!isSunny means the same as isSunny, and the extra marks only confuse the reader.
    • Thinking ! flips numbers. !5 is false, not -5. It asks whether the value counts as false and inverts the answer. The operator that changes a sign is the unary minus.
    • Forgetting the braces or putting else on its own line without a closing brace. The else must follow the block of the if.

    Key takeaways

    • ! turns true into false and false into true.
    • Put parentheses around a comparison you want to negate.
    • In TypeScript, ! also works on non-boolean values, using the rules for what counts as false.
    • If a negated condition has an else, check whether swapping the two blocks reads better.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free