I have three variables, variation, attribute and active for which I need to create an if statement for the following truth table:
variation
attribute
active
Result
[object Object]
'color'
true
TRUE
undefined
undefined
undefined
TRUE
[object Object]
'color'
false
FALSE
But I can't think of a smart and compact statement for the case, unless I write all desired true scenarios in an or separated long statement...
Can someone please help me with this?
Here is a quick fiddle for you.
TIA.
You can negate all the values to booleans and check if they are all equal:
!variation == !attribute && !attribute == !active
Values in JavaScript can be either truthy or falsy.
[object Object], 'color', true => truthy
undefined, false => falsy
So when you put the logical NOT operator (!) before a value, you effectively negate it, meaning all truthy values become the boolean false and all falsy values are cast to the boolean true.
Your truth table seems to return true when all of the variables are truthy or when all of the variables are falsy, and returns false when they are mixed.
So it essentially checks that all the values, when casted to booleans, are equal. So the condition above casts the values to opposite booleans and checks that they are all the same.
Related
I just learned there are truthy and falsy values in python which are different from the normal True and False.
Can someone please explain in depth what truthy and falsy values are? Where should I use them? What is the difference between truthy and True values and falsy and False values?
We use "truthy" and "falsy" to differentiate from the bool values True and False. A "truthy" value will satisfy the check performed by if or while statements. As explained in the documentation, all values are considered "truthy" except for the following, which are "falsy":
None
False
Numbers that are numerically equal to zero, including:
0
0.0
0j
decimal.Decimal(0)
fraction.Fraction(0, 1)
Empty sequences and collections, including:
[] - an empty list
{} - an empty dict
() - an empty tuple
set() - an empty set
'' - an empty str
b'' - an empty bytes
bytearray(b'') - an empty bytearray
memoryview(b'') - an empty memoryview
an empty range, like range(0)
objects for which
obj.__bool__() returns False
obj.__len__() returns 0, given that obj.__bool__ is undefined
As the comments described, it just refers to values which are evaluated to True or False.
For instance, to see if a list is not empty, instead of checking like this:
if len(my_list) != 0:
print("Not empty!")
You can simply do this:
if my_list:
print("Not empty!")
This is because some values, such as empty lists, are considered False when evaluated for a boolean value. Non-empty lists are True.
Similarly for the integer 0, the empty string "", and so on, for False, and non-zero integers, non-empty strings, and so on, for True.
The idea of terms like "truthy" and "falsy" simply refer to those values which are considered True in cases like those described above, and those which are considered False.
For example, an empty list ([]) is considered "falsy", and a non-empty list (for example, [1]) is considered "truthy".
See also this section of the documentation.
Python determines the truthiness by applying bool() to the type, which returns True or False which is used in an expression like if or while.
Here is an example for a custom class Vector2dand it's instance returning False when the magnitude (lenght of a vector) is 0, otherwise True.
import math
class Vector2d(object):
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def __abs__(self):
return math.hypot(self.x, self.y)
def __bool__(self):
return bool(abs(self))
a = Vector2d(0,0)
print(bool(a)) #False
b = Vector2d(10,0)
print(bool(b)) #True
Note: If we wouldn't have defined __bool__ it would always return True, as instances of a user-defined class are considered truthy by default.
Example from the book: "Fluent in Python, clear, concise and effective programming"
Truthy values refer to the objects used in a boolean context and not so much the boolean value that returns true or false.Take these as an example:
>>> bool([])
False
>>> bool([1])
True
>>> bool('')
False
>>> bool('hello')
True
Where should you use Truthy or Falsy values ?
These are syntactic sugar, so you can always avoid them, but using them can make your code more readable and make you more efficient.
Moreover, you will find them in many code examples, whether in python or not, because it is considered good practice.
As mentioned in the other answers, you can use them in if tests and while loops. Here are two other examples in python 3 with default values combined with or, s being a string variable. You will extend to similar situations as well.
Without truthy
if len(s) > 0:
print(s)
else:
print('Default value')
with truthy it is more concise:
print(s or 'Default value')
In python 3.8, we can take advantage of the assignment expression :=
without truthy
if len(s) == 0:
s = 'Default value'
do_something(s)
with truthy it is shorter too
s or (s := 'Default value')
do_something(s)
or even shorter,
do_something(s or (s := 'Default value'))
Without the assignment expression, one can do
s = s or 'Default value'
do_something(s)
but not shorter. Some people find the s =... line unsatisfactory because it corresponds to
if len(s)>0:
s = s # HERE is an extra useless assignment
else:
s = "Default value"
nevertheless you can adhere to this coding style if you feel comfortable with it.
Any object in Python can be tested for its truth value. It can be used in an if or while condition or as operand of the Boolean operations.
The following values are considered False:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.
All other values are considered True -- thus objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated.
In case of if (!id) {}
!expr returns false if its single operand can be converted to true; otherwise, returns true.
If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.
Examples of expressions that can be converted to false are:
null;
NaN;
0;
empty string ("" or '' or ``);
undefined.
Even though the ! operator can be used with operands that are not Boolean values, it can still be considered a boolean operator since its return value can always be converted to a boolean primitive. To explicitly convert its return value (or any expression in general) to the corresponding boolean value, use a double NOT operator or the Boolean constructor.
Example:
n1 = !null // !t returns true
n2 = !NaN // !f returns true
n3 = !'' // !f returns true
n4 = !'Cat' // !t returns false
While in case of if (id != null) {} it will only check if the value in id is not equal to null
reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT
Falsy means something empty like empty list,tuple, as any datatype having empty values or None.
Truthy means :
Except are Truthy
if(true){
alert("hello");
}
if("string"){
alert("hello");
}
The code above shows that a string can be used as a substitute for Boolean value "true". Why does this work and does this mean that Boolean value "true" and string have the same data type?
A string as a statement, represents it's existence, in other words, if the string is set, it will return true, as if its "" it will return as false
This way you can check a variable if it is set or not
JavaScript's conditional operators such as if-else and a ? b : c don't require the condition to be of actual Boolean type but rather check whether it is truthy or a falsy value in JavaScript terms.
For example, such values as null and 0 are considered falsy so they would be treated like false in if-else and ternary operators.
In a broader sense this might be considered as a case of type coercion, see for example this question for more information. So when an interpreter sees non-boolean expression inside an if it is "re-writing" it like if (Boolean("string")) { ... }, i.e. invoking conversion from the expression to the exact boolean type.
if("string"){
alert("hello");
}
since you did not include an operator, as default, it just checks for the existence of the string, "string" == true.
JavaScript has a boolean type, with possible values true and false (both of which are keywords.) Any value can be converted to a boolean according to the following rules:
false, 0, empty strings (""), NaN, null, and undefined all become false.
All other values become true.
You can perform this conversion explicitly using the Boolean() function:
Boolean(""); // false
Boolean(234); // true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
It may be that I'm just very groggy this morning, but I'm having trouble understanding why this returns as true:
_.some([null, 0, 'yes', false]); // true
I know that _.some() returns true if at least one of the elements passes the predicate test as true. But from my understanding, if no predicate is provided, _.identity() is used. But console.log-ing each of those elements individually with _.identity() didn't return true for any of them. So why does it return true?
Without a predicate, some uses identity, which uses the value itself, and 'yes' is truthy.
A quick dive through the annotated source (paying special attention to cb and the handling of missing predicates there) leaves you with, essentially, a coercion to boolean when they do:
if (predicate(obj[currentKey], currentKey, obj)) return true;
No predicate means you're working with the original value there, so if ('yes'), which is true.
You're not seeing true in the console for any of those values because _.identity will return the value itself (so 'yes') rather than coercing it to a boolean. If you were to do !!'yes' (coercion and double-not), you will see true.
'yes' is truthy:
_.some([null]) // false
_.some([0]) // false
_.some(['yes']) // true
_.some([false]) // false
From the Truth, equality in javascript link:
The construct if ( Expression ) Statement will coerce the result of evaluating the Expression to a boolean using the abstract method ToBoolean for which the ES5 spec defines the following algorithm:
string: The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
It doesn't need to return the literal value true, it only needs to return a truthy value (although you always should return only booleans).
The non-empty string 'yes' is truthy (you can test by Boolean('yes') or !!'yes').
Why does the following evaluate to 'hi'?
'hi' || true || 50
I'm not super new to javascript, but I'm rebeefing my knowledge by going through some old books and I for the life of me do not understand why this evaluates to 'hi' instead of true.. Can someone explain this??
Welcome to the world of truthy and falsey values.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This means that basically everything except
false
null
undefined
NaN
""
0
Will evaluate to true in || conditions, returning the first value that is truthy. This is sometimes used in a coalesce-like way:
a = a || {}
Which will set a to a if a is none of the values above, else an empty javascript object.
Because 'hi' is a non-empty string literal which evaluates to true when treated as a boolean. The expression a || b || c returns the first expression which evaluates to true, in this case 'hi'.
From MDN (Logical Operators):
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand can be converted to true; if both can be converted to false, returns false.
Hey thanks everybody for your input. Yeah, now it makes sense because I remember how the first value that evaluates to true is the one that it will evaluate to. I guess I have to do some more studying on the truthy stuff because yeah, it is simple, but in a way it is somewhat confusing at times. Thanks again!!
I understand that
if( value ) {
}
will evaluate to true if value IS NOT null, undefined, NaN, empty string (""), 0, or false
But, does
if (! value ) {}
evaluate to true if the value IS null, undefined, NaN, empty string (""), 0, or false ?
I am using Google Scripts and I am taking data from a spreadsheet in which some cells are blank. For those cells I want to be sure the value returns as "empty string" rather than any of the other possibilities like, undefined, for example (some are currently returning 'undefined' which is what led me to seek this answer).
I would like to use this code, as long as it does what I think it does:
if (! value ) {value = ""}
(P.S. I started at this thread: Is there a standard function to check for null, undefined, or blank variables in JavaScript?, but the answers do not address the opposite scenario)
In short, yes.
Coerce or cast the value to boolean by using the negative ! and double negative !! which will turn all falsey values to false and all other values to true, then just check wether its true or false knowing they're boolean.
So, in other words, if you want the boolean of the opposite, just prepend ! if you want the boolean of the actual value, prepend !!
!"" === true; //inverted
!!"" === false;//actual
Yes, those will evaluate to true:
if(!NaN){console.log('true!');}
true!
if(!undefined){console.log('true!');}
true!
if(!null){console.log('true!');}
true!
if(!''){console.log('true!');}
true!
if(!0){console.log('true!');}
true!