function boo(arr)
{
for(var i=0;i<arr.length;i++)
{
var bob = new Boolean(arr[i]);
if(bob === false)
{
console.log(arr[i]);
}
}
}
console.log(boo([0,"how",89,false]));
I want to check all the false values like false,null,undefined etc.from an array using Boolean Object and print it. How can i do it using Boolean Object?. How can i add multiple values for checking whether it is true or false in Boolean Object?
You can't compare Boolean objects that way in javascript. new Boolean(...) === false will always evaluate to false.
MDN has a good warning on the matter:
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.
For instance (given value = arr[i]), if you need to see if something is truthy just use !!value. For falsey, use !value. If you need to see if something is really true use value === true, likewise for false, but not a Boolean instance.
Related
I have the following pre-configuration
const preloadedConfig = {
"configA": null, // either true, false or null is allowed
};
and then I have the following initialization on page load
let finalConfig = preloadedConfig.configA || true;
The scenario:
Properties in the preloaded config can be changed to either true, false or null based on the user's preference
I wish to use short-circuit evaluation to determine the user choice on page load. If no choice(null) is supplied by the user, default the choice to true
My issue:
Based on the following extracted from here:
Falsy values are those who coerce to false when used in boolean context, and they are 0, null, undefined, an empty string, NaN and of course false.
The following is evaluated:
true >> evaluted true // ok
null >> evaluted true // ok
false >> evaluted true // the problem area
If the user supplies the config option of false, the final evaluated value will always result in true due to it being a "falsy value".
My desired outcome is a boolean value of false if the value supplied is false.
What should I do to make this work while using short-circuit evaluation and allowing 3 types of input values of null, true or false?
You can use the nullish coalescing operator instead.
let finalConfig = preloadedConfig.configA ?? true;
Alternatively, you can use a hasOwnProperty check.
let finalConfig = preloadedConfig.hasOwnProperty('configA') ? preloadedConfig.configA : true;
In modern environments (or with a transpiler), I'd use the nullish coalescing operator, which takes the right side only if the left side is null or undefined:
let finalConfig = preloadedConfig.configA ?? true;
Otherwise, use the conditional operator:
let finalConfig = preloadedConfig.configA == null ? true : preloadedConfig.configA;
You can make defaulting rule a bit better by using old Object.assign or modern destruct ... prop.
This will override configA even with null
const yourConfig = {
configA: true,
...preloadedConfig
}
With old env woudl be
Obejct.assign({configA: true},preloadedConfig)
EDIT:
Taking nulls as default would be
const yourConfig = {
configA: true,
...Object.fromEntries(Object.entries(preloadedConfig).filter(([key,val])=>val!==null))
}
I've been reviewing a case that looks like this:
loggedInUser$ = this.select().pipe(
filter(({ user }) => toBoolean(user)),
map(({ user: { firstName: f, lastName: l } }) => `${f} ${l}`)
);
Just curious whether we could always substitute !! in place of this method to get a boolean and whether. IIUC the semantics would always be the same?
In other words we should always be able to replace toBoolean(...) with !!?
The implementation looks like this:
// #internal
export function toBoolean(value: any): boolean
{
return value != null && `${value}` !== 'false';
}
Analysis
So based on the answers the difference is that !! returns true for 'false', but toBoolean() returns false for 'false'.
This is a bit subjective, but personally I feel that it's better to tell users to use !! than some other sugared approach, since we should be familiar with the Javascript basics / semantics first and then build out from that.
Thus if anyone wants 'false' to be false, then they have to implement that explicitly. The application in this case would be that someones name is actually 'false` and we want to allow that to be true.
No, your toBoolean and !! are not semantically equivalent. toBoolean depends on string serialisation, which is a rather weird way to cast a value to a boolean. Here are a few values that lead to different results:
toBoolean(0) == true
toBoolean('false') == false
toBoolean('') == true
toBoolean({toString(){return "false"}}) == false
No, !! is not equivalent to toBoolean.
To explain a bit further, !! will always return a Boolean value MDN even has a note on the usage of !!:
It is possible to use a couple of NOT operators in series to explicitly force the conversion of any value to the corresponding boolean primitive. The conversion is based on the "truthyness" or "falsyness" of the value (see truthy and falsy).
The same conversion can be done through the Boolean function.
So you can always replace Boolean(x) with !!x, but what about toBoolean? Notice that toBoolean converts its parameter to a string and compares that to the string 'false', so there's at least one case where it's not the same:
function toBoolean(value: any): boolean
{
return value != null && `${value}` !== 'false';
}
console.log(Boolean('false'))
console.log(toBoolean('false'))
And to show a more subtle issue:
function toBoolean(value: any): boolean
{
return value != null && `${value}` !== 'false';
}
const foo = { toString: () => 'false' };
console.log(Boolean(foo))
console.log(toBoolean(foo))
I have an object and I need to check if all the values are true.
{
condition1: true,
condition2: true,
condition3: false
}
Ive used Object.value to get an array of the true and false values. However I cant seem to get the every function to work, it always returns true.
const test = Object.values(equipmentSelection)
.every((element) => {
if (element = true) return true;
});
Just return the element without using conditional check, you can do like this
const test = Object.values(equipmentSelection)
.every(element => element)
});
You are using an assignment operator = instead of a logical == or === operator. So you are basically setting element to be equal to true and then use this same value (true) as the condition of if. So the if condition is always true and thus true is returned for each element in the array.
Since element is of type boolean, you don't need the if statement, just use its value:
.every(element => element);
You can do this.
const test = Object.values(equipmentSelection)
.every(element => element===true);
And like others have said,
.every( element => element);
Will return the elements value which is with true or false and that’s what you will get with the comparisons.
This question already has answers here:
Why does !new Boolean(false) equals false in JavaScript?
(2 answers)
Closed 6 years ago.
Why logical not operator in javascript returns different result between Boolean value and Boolean object? Consider the following example.
!true // false
!false // true
!(new Boolean(true)) // false
!(new Boolean(false)) // false
From the spec, it says that the value being evaluated converted ToBoolean. ToBoolean will return true if the argument is an Object, and return as is if the argument is a Boolean.
Digging further, ToBoolean also being used in other places like if statement and conditional operator, consider the following example:
var a = (new Boolean(false)) ? "unexpected" : "expected";
console.log(a); // unexpected
The question: is Boolean object an Object, or a Boolean? Should we not evaluate Boolean object as a Boolean?
UPDATE
My question was marked as duplicate question with this. That question doesn't have a satisfactory answers because none answers my question, Is Boolean object an Object, or a Boolean? Should we not evaluate Boolean object as a Boolean?
Simply knowing Boolean object is an object is not enough, why does it even exists and what is the proper way of dealing and/or designing objects with Boolean object still left unanswered.
An object, no matter if it has properties or not, never defaults to false...
new Boolean(true) will return an object not Boolean and !{} is always going to be false as {} is a truthy value (Boolean({}) will be evaluated as true)
While dealing with Boolean factory function, do not create new instance using new (as it will create new instance of Boolean and will return an object)
Boolean(INPUT) will return primitive-Boolean value of the specified expression which could be used for comparison
From docs, The Boolean object is an object wrapper for a boolean value()
Description: The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true "when passed to a conditional statement."[Reference]
For example, the condition in the following if statement evaluates to true
var x = new Boolean("false");
if (x) {
console.log('x is true');
}
var y = new Boolean(false);
if (y) {
console.log('y is true');
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Boolean is a function. Depending on the invocation type, it has different behavior in terms of truthy and falsy.
1. Invoking as a simple function
When calling Boolean(value) as a simple function, it verifies if the argument is a falsy (false, null, undefined, '', 0,Nan) or truthy (all other values: object instances, 1, true, etc). This type of invocation returns a boolean primitive type.
It works as expected:
Boolean(null) // prints false
Boolean(0) // prints false
Boolean({}) // prints true
Boolean(-1) // prints true
2. Invoking as a constructor
Like any function in JavaScript, Boolean can be invoked as a constructor: var b = new Boolean(value). This invocation type returns a boolean object instance.
This introduces confusing because JavaScript treats object instances as truthy value.
var b = new Boolean(null);
!!b // prints true, because b is an object instance
if (b) { // b evaluates to true
//executed code
}
2.1 Why invoking as a constructor is possible
JavaScript allows this constructor invocation to give developer a mechanism to preserve properties creation for a boolean. A primitive boolean type doesn't save properties assigned to it.
var booleanObject = new Boolean(null);
booleanObject.foo = 'bar'; // create a property
booleanObject.foo // prints 'bar'
var booleanPrimitive = false;
booleanPrimitive.foo = 'bar'; // create a property
booleanPrimitive.foo // prints undefined
2.2 How to make the Boolean object work
Nevertheless, new Boolean(value) has a mechanism to do comparison. Like any JavaScript object, it has a method valueOf(), which returns the transformation of the value to a boolean primitive type (true for truthy and false for falsy):
var falsyBoolean = new Boolean(null);
falsyBoolean.valueOf() // prints false, because null is falsy
var truthyBoolean = new Boolean(1);
truthyBoolean.valueOf() // prints true, because 1 is truthy
To make this work in conditionals, it is necessary to avoid any transformations of the boolean object instance into a truthy value. To make this happen, use comparison operator == directly:
var falsyBoolean = new Boolean(null);
falsyBoolean == false ? 'falsy' : 'truthy' // prints expected 'falsy'
if (falsyBoolean == false) {
//executed code
}
If an operand in == operator is an object and other a primitive type, JavaScript transforms it into a primitive type, which actually consists in calling the valueOf() method on the boolean object. See more details in this article.
3. How not to get confused
The best rule is to avoid using Boolean as object instances at all. Boolean(value) or !!value is enough to verify the variable truthy state.
From MDN's entry on Boolean:
Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.
For example, the condition in the following if statement evaluates to true:
var x = new Boolean("false");
if (x) {
// this code is executed
}
var y = new Boolean(false);
if (y) {
// this code is also executed
}
You will get same result for true and false parameters when using new Boolean(...)
Object-Oriented JavaScript Book, Stoyan Stefanov:
You can convert any value to its Boolean equivalent using a double negation.
Understanding how any value converts to a Boolean is important. Most values
convert to true with the exception of the following, which convert to false
"" null undefined 0 NaN false
So !!{}, !!new Boolean(true), !!new Boolean(false) return always true
This condition (without double negation):
if (new Boolean(true) === true) {
console.log('this string will never be printed');
}
returns false, because there are different types:
typeof new Boolean(true); // "object"
typeof true; // "boolean"
You have to compare them only by value to get an expected result:
if (new Boolean(true) == true) {
console.log('Yay!');
}
new Boolean(true) == true; // true
new Boolean(true) === true; // false
Another example:
if (new Boolean(true) === new Boolean(true)) {
console.log('this string will never be printed')
}
In this case you are trying to compare objects. You will get the same result both with == and === compare operators.
Object-Oriented JavaScript Book, Stoyan Stefanov: When you compare objects, you'll get true only if you compare two
references to the same object. Comparing two distinct objects that
happen to have the exact same methods and properties returns false.
Do not use a Boolean object new Boolean(...) in place of a Boolean primitive.
Just tried out the folliwng:
alert(typeof true); //alerts boolean
alert(typeof new Boolean(true)); //alert object
alert(typeof !(new Boolean(true))); //alerts boolean
alert(!(new Boolean(true))); //alerts false
Both Rayon and Mukul are right, you just need to use !Boolean(false) //returns true as a boolean value.
The Boolean type has two literal
values: true and false.
Do not confuse the primitive Boolean
values true and false with the true
and false values of the Boolean
object. The Boolean object is a
wrapper around the primitive Boolean
data type. See Boolean Object for more
information.
What does this mean? What's the difference between the Boolean object and the Boolean data type??
This is a boolean value:
true
This is a Boolean object wrapping the value:
new Boolean(true);
Having the object adds a level of indirection. Try this to see the difference:
var a = true;
var b = true;
var c = new Boolean(true);
var d = new Boolean(true);
alert(a == b); // true - two `true` values are equal.
alert(c == d); // false - they are not the same object.
See also:
What is the purpose of new Boolean() in Javascript?
I want to add to other answers that a Boolean object can also be null, but a boolean value cannot.
The boolean data type is a value that can only be true or false. The Boolean object is an object that represents a boolean value.
The Boolean Data Type is the 'boolean' (TRUE or FALSE) whereas the Boolean Object is an object that translates values INTO boolean data
You'll find an explanation here
w3schools