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!
Related
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.
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
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've come across this javascript code in the wild and am having trouble understanding exactly what it does and how it works:
// Ensure its bool.
options.something = (!(options.something === false));
From what I can tell, options.something is just being set to the opposite of false. Is there any functional difference between the above and just doing the following instead?
options.something = true;
JSHint and JSLint appropriately give a "confusing use of '!'" warning on the original code.
Interesting piece of code. The only way options.something will be assigned false is if it is itself false.
Let's break it down:
(!(options.something === false)) =>
(!(false === false)) =>
(!true) =>
false
So, at then end of the day the code ensures that options.something is either true or false, and the only way it can be false is if it actually is the value false (not undefined, null, 0, etc.).
On the other hand, it will be the value true if it begins as anything else (such as undefined, null, 0, etc.).
It's not actually a toggle, it's a check that the value is a boolean.
Read it from the inside out.
Inner parenthesis asks if something is false. If it is the value of the expression is true (false does equal false). Take the negative of that (! true) which returns the boolean value false.
If something is true, the inner expression is false, true != false. Take the negative of that (! false) and the result is true.
OK, so what if something is undefined? Undefined will evaluate as false and since false === false the expression is true. Negating that (! true) returns false.
So anything that is true is returned as true and undefined or false values always return false.
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
I am by no means an expert at Javascript, but I have been reading Mark Pilgrim's "Dive into HTML5" webpage and he mentioned something that I would like a better understanding of.
He states:
Finally, you use the double-negative trick to force the result to a Boolean value (true or false).
function supports_canvas() {
return !!document.createElement('canvas').getContext;
}
If anyone can explain this a little better I would appreciate it!
A logical NOT operator ! converts a value to a boolean that is the opposite of its logical value.
The second ! converts the previous boolean result back to the boolean representation of its original logical value.
From these docs for the Logical NOT operator:
Returns false if its single operand can be converted to true; otherwise, returns true.
So if getContext gives you a "falsey" value, the !! will make it return the boolean value false. Otherwise it will return true.
The "falsey" values are:
false
NaN
undefined
null
"" (empty string)
0
Javascript has a confusing set of rules for what is considered "true" and "false" when placed in a context where a Boolean is expected. But the logical-NOT operator, !, always produces a proper Boolean value (one of the constants true and false). By chaining two of them, the idiom !!expression produces a proper Boolean with the same truthiness as the original expression.
Why would you bother? Because it makes functions like the one you show more predictable. If it didn't have the double negative in there, it might return undefined, a Function object, or something not entirely unlike a Function object. If the caller of this function does something weird with the return value, the overall code might misbehave ("weird" here means "anything but an operation that enforces Boolean context"). The double-negative idiom prevents this.
In javascript, using the "bang" operator (!) will return true if the given value is true, 1, not null, etc. It will return false if the value is undefined, null, 0, or an empty string.
So the bang operator will always return a boolean value, but it will represent the opposite value of what you began with. If you take the result of that operation and "bang" it again, you can reverse it again, but still end up with a boolean (and not undefined, null, etc).
Using the bang twice will take a value that could have been undefined, null, etc, and make it just plain false. It will take a value that could have been 1, "true", etc. and make it just plain true.
The code could have been written:
var context = document.createElement('canvas').getContext;
var contextDoesNotExist = !context;
var contextExists = !contextDoesNotExist;
return contextExists;
Using !!variable gives you a guarantee of typecast to boolean.
To give you a simple example:
"" == false (is true)
"" === false (is false)
!!"" == false (is true)
!!"" === false (is true)
But it doesn't make sense to use if you are doing something like:
var a = ""; // or a = null; or a = undefined ...
if(!!a){
...
The if will cast it to boolean so there is no need to make the implicit double negative cast.
! casts "something"/"anything" to a boolean.
!! gives the original boolean value back (and guarantees the expression is a boolean now, regardless to what is was before)
The first ! coerces the variable to a boolean type and inverts it. The second ! inverts it again (giving you the original (correct) boolean value for whatever you are checking).
For clarity you would be better off using
return Boolean(....);
document.createElement('canvas').getContext may evaluate to either undefined or an object reference. !undefined yields true, ![some_object] yields false. This is almost what we need, just inverted. So !! serves to convert undefined to false and an object reference to true.
It's to do with JavaScript's weak typing. document.createElement('canvas').getContext is a function object. By prepending a single ! it evaluates it as a boolean expression and flips the answer around. By prepending another !, it flips the answer back. The end result is that the function evaluates it as a boolean expression, but returns an actual boolean result rather than the function object itself. Prepending !! is a quick and dirty way to typecast an expression to a boolean type.
If document.createElement('canvas').getContext isn't undefined or null, it will return true. Otherwise it will return false.