Object does not equal to true or false - javascript

So my uploaded media file (event.target.files[0]) does not equal to true or false.
It has a typeof object.
It's part of some form state and I'd like to check the object whether all fields are not empty "".
I thought a JS object should always === true, but maybe this is different for 'files' objects?

=== checks for strict equality, so the two values must be exactly the same.
An object is truthy, but does not equal true, so what you are really doing is { ... } === true, which is false.
If you want to check if none of the object's values are empty, you can filter for empty values:
const empty = Object.keys(theObject).length === 0 || Object.values(theObject).filter(value => {
return value.trim() === '';
}).length > 0;

=== tests for equal value and equal type (ref). typeof(true) is boolean but a file is not a boolean. So the comparison will never yield true.
See also https://stackoverflow.com/a/8511350/4640820

To check the type of a value, you must write
if( (typeof <your value>) == ("<expected type>")){
...
}
For example, a statement like this:
if( (typeof 42)=="number" )
is true.
Reference for most cases of typeof

Related

javascript and (&&) operator not working as expected

I need to check if a string is equal to a defined value AND if the object has the hash key.
I am very confused with this:
var my_string = 'some_string';
var my_obj = {'hash':'4010f89a05c236cd4f3a5c7558af0e70dc4216454d2d5155a285bfbad752ce51f9510272821a254'}
console.log((my_string == 'some_string' && my_obj['hash']));
That return 4010f89a05c236cd4f3a5c7558af0e70dc4216454d2d5155a285bfbad752ce51f9510272821a254
Expected true or false (in this example expected true).
It's working correctly.
(my_string == 'some_string' && my_obj['hash']) is equal to "4010f89a05c236cd4f3a5c755..." which is truthy. This is just fine to use as a conditional in an if statement for instance.
You can convert it to an actual boolean too:
!!(my_string == 'some_string' && my_obj['hash'])
The && operator returns whatever is on the right side of the && whenever both values are true like this:
const foo = 'foo';
const bar = 'bar';
const foobar = foo && bar;
console.log(foobar);
This returned result is then in turn coerced into a true of false as the result of the if statement. It is important to realise that the if statement coerces the value into a boolean and the && statement does not.
One option is to use the in operator to check to see if a particular key exists in the object. I prefer this method because JavaScript has some really really awful values that are considered falsey, like 0.
console.log((my_string == 'some_string' && ('hash' in my_obj)));
&& does not return everytime boolean.
When you use && with string it returns the second value when both are true.
When you use || with string it returns the first value when both are true.
let one = "Cat" && "Dog"
let zwo = "Cat" || "Apple"
one returns Dog. two returns Cat
You can use a ternary operation and make it return true or false.
Like so:
console.log( (my_string == 'some_string' && my_obj['hash']) ? true : false );
More info here:
https://www.w3schools.com/jsref/jsref_operators.asp (search for "Conditional (Ternary) Operator")
https://learn.microsoft.com/en-us/scripting/javascript/reference/conditional-ternary-operator-decrement-javascript

Difference between exclamation equals sign and exlamation 2x equals sign when checking with null

What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.

how to check falsy with undefined or null?

undefined and null are falsy in javascript but,
var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}
but it returns 'has value' when tried in console, why not 'null' ?
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle
A value being "falsy" means that the result of converting it to a Boolean is false:
Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true
This is very different from comparing it against a Boolean:
null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal
Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.
But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.
Depending on what exactly you want to test for, you have a couple of options:
if (!value) // true for all falsy values
if (value == null) // true for null and undefined
if (value === null) // true for null
In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.
=== checks for identity - the exact same type and value. So null !== false firstly because they are not the same type, thus will not match when using ===.
If you just want to check for any falsey value, then check with:
if (!n)
If you want to specifically check for null, then check for null like this:
if (n === null)

How do i compare against an empty variable?

If I set a variable to 0, I get the weird behavior that a comparison to "" (empty) is true. How do I check that the variable is really empty?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
Use strict comparison operators
=== and !==
With == and != (called abstract comparison operators),
If the two operands are not of the same type, JavaScript attempts to
convert the operands to an appropriate type for the comparison.
If by empty, you want to check if the variable hasn't been defined, use:
if (typeof tmp !== "undefined") {
// it exists!
}
What do you mean by empty variable? If you mean an empty string, then you should use !== to check it.
if (tmp !== "")
JavaScript implicitly converts values to other types. To check type also, use the !== operator:
if ( tmp !== "")
In JavaScript everything except 0, NaN, undefined, false and null are considered to be false. "" is considered as true.
if (tmp) {
}
Above if will be executed if variable contains any value other than 0, NaN, undefined, false and null.
If tmp is a string then you can use the following code:
if (tmp !== "") {
}
=== and !== operators compare without doing type-conversion.

Checking whether a variable is null or NOT

var DEST_VALUE = 1
var APPDAYS_AFTER = 2
}
How can i check whether the variable holds some value or not. When i do this, it does not work...
Of course it doesn't do anything, because in your example DEST_VALUE resolves to true like APPDAYS_AFTER. Value that resolve to false when converted to a boolean in javascript are:
false
null
undefined
The empty string ''
The number 0
The number NaN (yep, 'Not a Number' is a number, it is a special number)
if you write
if(!DEST_VALUE){
txtSiteId.value = fileContents.Settings.SiteID;
}
you write "if DEST_VALUE is not true do something" (in your case it does nothing). If you want to check if a variables hold a value:
if(DEST_VALUE !== undefined){
//do something
}
I use such function to check if variable is empty or not:
function empty( mixed_var ) {
return ( typeof(mixed_var) === 'undefined' || mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false );
}
I assume you mean "holds some value" like in "the variable has been created so it exists", right? Otherwise, your approach works perfectly fine.
If you want to check whether a variable exists in javascript, you have to check its parent object for the property - otherwise the script will fail. Each object in javascript belongs to a parent object, even if it seems to be global (then, it belongs to the window object). So, try something like:
if (window.DEST_VALUE)
// do something

Categories