Lessons · TypeScript · ! flips true and false
Flipping a condition
! turns true into false and false into true. Applied to a non-boolean it first converts the value to a boolean, which is why !0 is true.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
'While not ready', 'if no items', 'unless logged in': half of all conditions are negations, and ! is how they are written.
How to think about it
Read !x as 'x is falsy'. When negating a comparison, parenthesise it: !(a === b), or write a !== b, which is clearer still.
Worked example
console.log(!true);false.
console.log(!0, !"");true true: 0 and the empty string are falsy, so their nots are true.
console.log(!"hi");false: a non-empty string is truthy.
console.log(!(3 > 5));true: negate the whole comparison.
Your turn
Wait while not ready.
if (isReady) { wait(); }Solve one with the tests running
The trap
!x == y is (!x) == y. The not binds tighter than the comparison, so parenthesise what you mean to negate.
Practise ! flips true and false on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.