The not operator is the simplest and operates on a single Boolean value. It “inverts” a Boolean value from true to false and false to true:
print(not true) --Output: false
print(not false) --Output: true
You can chain several nots together:
print(not not not not not false) --Output: true
But what happens if we try to use a logical operator on a non-Boolean data type?
Let’s find out:
print(not "Hello world!") --Output: false
print(not 3.14) --Output: false
Huh?
So if not‘ing a string or number data type makes it false, then that must mean string and numbers are true, right?
print("Hello world!" == true) --Output: false
print(3.14 == true) --Output: false
Wait, what? They’re not false but not true either, yet somehow evaluate to false when not‘ed?!
What about nil?
print(not nil) ---Output: true
print(nil == false) --Output: false
print(nil == true) --Output: false
!!!
Truth
Logical operators can only work with true or false values. So when a logical operator encounters a non-Boolean value, it needs to know how to interpret those values.
‘Truthiness‘ is the concept of how to interpret non-Boolean values in a Boolean expression.
This is pre-defined by the language.
In the preceding examples, you saw that strings and numbers are not the same as true but when used in a Boolean expression, they were evaluated as “true-like.”
Likewise, nil is evaluated as “false-like.”
We’ll return to this in a bit, but to summarize, only false is false and only true is true. When evaluated in a Boolean expression, nil is “falsy” and everything else is “truthy.”