Javascript booleans: false && true results in true - javascript

I need to disable/enable a button depending in on the value of some radio groups. These radios are populated by some groovy code becasue I'm using grails, a framework for groovy, that is a superset of java. Well that explanation was to say that the values of the radios are defined as booleans, which is just natural because they correspond to yes/no answers.
Now, to disable/enable this button I use some javascript, but it goes bananas with boolean values. As the title states, on some point I do a logical and between a variable that holds false and another variable that holds true
Here is the peice of problematic code:
var actual = true;
$('.requerido input:radio:checked').each(function() {
console.log("actual: " + actual);
console.log("value: " + this.value);
console.log("actual and value: " + (actual && this.value));
actual = actual && this.value;
console.log("actual: " + actual);
});
As you can see I use the console.log for debugging, and this is what throws at some point:
actual: true
value: true
actual and value: true
actual: true
actual: true
value: false
actual and value: false
actual: false
actual: false
value: true
actual and value: true
actual: true
So true && false == false, but false && true == true ? Note that the values have no quotes, so they are boolean values (I'm debugging using the Chrome console which represent strings inside double quotes, so you can distinguish between true and "true").
Any ideas?
Also, doing a manual comparison like var x = true && false always works as expected, is juts with variables that the problem is present.

The this.value from your checked radio button input is not actually a boolean it is a string. The comparison of strings and boolean values can cause issues like this. It is one of the reasons why it is considered best practise is to use === for comparison.
See this SO Question for full details; JavaScript === vs == : Does it matter which β€œequal” operator I use?

Note that the && does the following:
Returns expr1 if it can be converted to false; otherwise, returns
expr2.
source
So in cases like:
var truish=true;//interchangeable with anything different than 0,"",false,null,undefined,NaN
var falsish=null;//interchangeable with 0,"",false,null,undefined,NaN
alert(truish&&falsish);//null (falsish was returned)
The returned value isn't necessarily a boolean, a solution to this would be to force a boolean !(x&&y)
So my guess is that something like this is happening

if you are trying to calculate with logic operators, remember:
var result = true && "false";// always results (string) "false"
var result = true && "true";// always results (string) "true"
var result = false && "true";// always results (boolean) false
var result = false && "false";// always results (boolean) false
var result = "true" && true;// always results (boolean) true
var result = "true" && false;// always results (boolean) false
var result = "false" && true;// always results (boolean) true
var result = "false" && false;// always results (boolean) false
var result = "true" && "true";// always results (string)"true"
var result = "true" && "false";// always results (string) "false"
var result = "false" && "true";// always results (string) "true"
var result = "false" && "false";// always results (string) "false"
because:
javascript judge the first operand, if true it will return the second operand, or else return false; it just like:
var first = true
var second = "false";
if (first) {
result = second;
} else {
result = false;
}
or
result = first ? second : false;
this is the way javascript logic operator actually works.
you must perform strict comparison between different variable types:
result = true && (value==="false");
strings not empty is equal to (boolean)true, even "false".
and remember that html element attributes are "String"s

This must have to do something with (one of) the values of your radio controls, because in plain javascript this evaluates as expected:
function boolx(tf,val){
var test = tf && val;
console.log([tf,val,tf && val,test]);
}
tf(true,false); //=> [true,false,false,false]
tf(false,true); //=> [false,true,false,false]
Maybe an explicit conversion of this.value helps, because this.value is actually a string:
var actual = true;
$('.requerido input:radio:checked').each(function() {
var val = /true/i.test(this.value);
console.log("actual: " + actual);
console.log("value: " + val);
console.log("actual and value: " + (actual && val));
actual = actual && val;
console.log("actual: " + actual);
});

Try a bitwise and & vice &&. The later would be appropriate in a conditional comparison, but not in assigning a value to a variable.

Is this really what you want to do? :
actual = actual && this.value;
That's the same as:
if (actual) {
actual = this.value;
}
actual is always true as defined in your code, so actual would be this.value and not a boolean.

Related

Javascript wrong output [duplicate]

Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?
I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.
The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.
var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
Is there a better way to accomplish this?
Do:
var isTrueSet = (myValue === 'true');
using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types.
This will set isTrueSet to a boolean true if the string is "true" and boolean false if it is string "false" or not set at all.
For making it case-insensitive, try:
var isTrueSet = /^true$/i.test(myValue);
// or
var isTrueSet = (myValue?.toLowerCase?.() === 'true');
// or
var isTrueSet = (String(myValue).toLowerCase() === 'true');
Don't:
You should probably be cautious about using these two methods for your specific needs:
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.
Warning
This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".
An invalid json string passed into these functions below WILL throw an exception.
Original answer:
How about?
JSON.parse("True".toLowerCase());
or with jQuery
$.parseJSON("TRUE".toLowerCase());
const stringToBoolean = (stringValue) => {
switch(stringValue?.toLowerCase()?.trim()){
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
case undefined:
return false;
default:
return JSON.parse(stringValue);
}
}
I think this is much universal:
if (String(a).toLowerCase() == "true") ...
It goes:
String(true) == "true" //returns true
String(false) == "true" //returns false
String("true") == "true" //returns true
String("false") == "true" //returns false
Remember to match case:
var isTrueSet = (myValue.toLowerCase() === 'true');
Also, if it's a form element checkbox, you can also detect if the checkbox is checked:
var isTrueSet = document.myForm.IS_TRUE.checked;
Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.
This is the easiest way to do boolean conversion I came across recently. Thought of adding it.
JSON.parse('true');
let trueResponse = JSON.parse('true');
let falseResponse = JSON.parse('false');
console.log(trueResponse);
console.log(falseResponse);
You can use regular expressions:
/*
* Converts a string to a bool.
*
* This conversion will:
*
* - match 'true', 'on', or '1' as true.
* - ignore all white-space padding
* - ignore capitalization (case).
*
* ' tRue ','ON', and '1 ' will all evaluate as true.
*
*/
function strToBool(s)
{
// will match one and only one of the string 'true','1', or 'on' rerardless
// of capitalization and regardless off surrounding white-space.
//
regex=/^\s*(true|1|on)\s*$/i
return regex.test(s);
}
If you like extending the String class you can do:
String.prototype.bool = function() {
return strToBool(this);
};
alert("true".bool());
For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:
Object.defineProperty(String.prototype, "com_example_bool", {
get : function() {
return (/^(true|1)$/i).test(this);
}
});
alert("true".com_example_bool);
(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. Bug 720760)
Wood-eye be careful.
After seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:
Let's start with the shortest, but very strict way:
var str = "true";
var mybool = JSON.parse(str);
And end with a proper, more tolerant way:
var parseBool = function(str, strict)
{
// console.log(typeof str);
// strict: JSON.parse(str)
if (str == null)
{
if (strict)
throw new Error("Parameter 'str' is null or undefined.");
return false;
}
if (typeof str === 'boolean')
{
return (str === true);
}
if(typeof str === 'string')
{
if(str == "")
return false;
str = str.replace(/^\s+|\s+$/g, '');
if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')
return true;
str = str.replace(/,/g, '.');
str = str.replace(/^\s*\-\s*/g, '-');
}
// var isNum = string.match(/^[0-9]+$/) != null;
// var isNum = /^\d+$/.test(str);
if(!isNaN(str))
return (parseFloat(str) != 0);
return false;
}
Testing:
var array_1 = new Array(true, 1, "1",-1, "-1", " - 1", "true", "TrUe", " true ", " TrUe", 1/0, "1.5", "1,5", 1.5, 5, -3, -0.1, 0.1, " - 0.1", Infinity, "Infinity", -Infinity, "-Infinity"," - Infinity", " yEs");
var array_2 = new Array(null, "", false, "false", " false ", " f alse", "FaLsE", 0, "00", "1/0", 0.0, "0.0", "0,0", "100a", "1 00", " 0 ", 0.0, "0.0", -0.0, "-0.0", " -1a ", "abc");
for(var i =0; i < array_1.length;++i){ console.log("array_1["+i+"] ("+array_1[i]+"): " + parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log("array_2["+i+"] ("+array_2[i]+"): " + parseBool(array_2[i]));}
for(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}
for(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}
I thought that #Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:
function isTrue(value){
if (typeof(value) === 'string'){
value = value.trim().toLowerCase();
}
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
It's not necessary to cover all the false cases if you already know all of the true cases you'd have to account for. You can pass anything into this method that could pass for a true value (or add others, it's pretty straightforward), and everything else would be considered false
Universal solution with JSON parse:
function getBool(val) {
return !!JSON.parse(String(val).toLowerCase());
}
getBool("1"); //true
getBool("0"); //false
getBool("true"); //true
getBool("false"); //false
getBool("TRUE"); //true
getBool("FALSE"); //false
UPDATE (without JSON):
function getBool(val){
var num = +val;
return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');
}
I also created fiddle to test it http://jsfiddle.net/remunda/2GRhG/
Your solution is fine.
Using === would just be silly in this case, as the field's value will always be a String.
The Boolean object doesn't have a 'parse' method. Boolean('false') returns true, so that won't work. !!'false' also returns true, so that won't work also.
If you want string 'true' to return boolean true and string 'false' to return boolean false, then the simplest solution is to use eval(). eval('true') returns true and eval('false') returns false.
Keep in mind the performance and security implications when using eval() though.
var falsy = /^(?:f(?:alse)?|no?|0+)$/i;
Boolean.parse = function(val) {
return !falsy.test(val) && !!val;
};
This returns false for every falsy value and true for every truthy value except for 'false', 'f', 'no', 'n', and '0' (case-insensitive).
// False
Boolean.parse(false);
Boolean.parse('false');
Boolean.parse('False');
Boolean.parse('FALSE');
Boolean.parse('f');
Boolean.parse('F');
Boolean.parse('no');
Boolean.parse('No');
Boolean.parse('NO');
Boolean.parse('n');
Boolean.parse('N');
Boolean.parse('0');
Boolean.parse('');
Boolean.parse(0);
Boolean.parse(null);
Boolean.parse(undefined);
Boolean.parse(NaN);
Boolean.parse();
//True
Boolean.parse(true);
Boolean.parse('true');
Boolean.parse('True');
Boolean.parse('t');
Boolean.parse('yes');
Boolean.parse('YES');
Boolean.parse('y');
Boolean.parse('1');
Boolean.parse('foo');
Boolean.parse({});
Boolean.parse(1);
Boolean.parse(-1);
Boolean.parse(new Date());
There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create this jsPerf that I hope can throw some light here.
Brief of results (the higher the better):
Conditional statement: 2,826,922
Switch case on Bool object: 2,825,469
Casting to JSON: 1,867,774
!! conversions: 805,322
Prototype of String: 713,637
They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.
This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive
var isTrueSet = (myValue.toLowerCase() === 'true');
I use the following:
function parseBool(b) {
return !(/^(false|0)$/i).test(b) && !!b;
}
This function performs the usual Boolean coercion with the exception of the strings "false" (case insensitive) and "0".
The expression you're looking for simply is
/^true$/i.test(myValue)
as in
var isTrueSet = /^true$/i.test(myValue);
This tests myValue against a regular expression , case-insensitive, and doesn't modify the prototype.
Examples:
/^true$/i.test("true"); // true
/^true$/i.test("TRUE"); // true
/^true$/i.test("tRuE"); // true
/^true$/i.test(" tRuE"); // false (notice the space at the beginning)
/^true$/i.test("untrue"); // false (some other solutions here will incorrectly return true
/^true$/i.test("false");// returns false
/^true$/i.test("xyz"); // returns false
Simplest solution πŸ™ŒπŸ½
with ES6+
use the logical NOT twice [ !! ] to get the string converted
Just paste this expression...
const stringToBoolean = (string) => string === 'false' ? false : !!string
And pass your string to it!
stringToBoolean('') // false
stringToBoolean('false') // false
stringToBoolean('true') // true
stringToBoolean('hello my friend!') // true
πŸ€™πŸ½ Bonus! πŸ€™πŸ½
const betterStringToBoolean = (string) =>
string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?
false : !!string
You can include other strings at will to easily extend the usage of this expression...:
betterStringToBoolean('undefined') // false
betterStringToBoolean('null') // false
betterStringToBoolean('0') // false
betterStringToBoolean('false') // false
betterStringToBoolean('') // false
betterStringToBoolean('true') // true
betterStringToBoolean('anything else') // true
you can use JSON.parse as follows:
var trueOrFalse='True';
result =JSON.parse(trueOrFalse.toLowerCase());
if(result==true)
alert('this is true');
else
alert('this is false');
in this case .toLowerCase is important
Boolean.parse = function (str) {
switch (str.toLowerCase ()) {
case "true":
return true;
case "false":
return false;
default:
throw new Error ("Boolean.parse: Cannot convert string to boolean.");
}
};
There are already so many answers available. But following can be useful in some scenarios.
// One can specify all values against which you consider truthy
var TRUTHY_VALUES = [true, 'true', 1];
function getBoolean(a) {
return TRUTHY_VALUES.some(function(t) {
return t === a;
});
}
This can be useful where one examples with non-boolean values.
getBoolean('aa'); // false
getBoolean(false); //false
getBoolean('false'); //false
getBoolean('true'); // true
getBoolean(true); // true
getBoolean(1); // true
To convert both string("true", "false") and boolean to boolean
('' + flag) === "true"
Where flag can be
var flag = true
var flag = "true"
var flag = false
var flag = "false"
I'm suprised that includes was not suggested
let bool = "false"
bool = !["false", "0", 0].includes(bool)
You can modify the check for truely or include more conditions (e.g. null, '').
This function can handle string as well as Boolean true/false.
function stringToBoolean(val){
var a = {
'true':true,
'false':false
};
return a[val];
}
Demonstration below:
function stringToBoolean(val) {
var a = {
'true': true,
'false': false
};
return a[val];
}
console.log(stringToBoolean("true"));
console.log(typeof(stringToBoolean("true")));
console.log(stringToBoolean("false"));
console.log(typeof(stringToBoolean("false")));
console.log(stringToBoolean(true));
console.log(typeof(stringToBoolean(true)));
console.log(stringToBoolean(false));
console.log(typeof(stringToBoolean(false)));
console.log("=============================================");
// what if value was undefined?
console.log("undefined result: " + stringToBoolean(undefined));
console.log("type of undefined result: " + typeof(stringToBoolean(undefined)));
console.log("=============================================");
// what if value was an unrelated string?
console.log("unrelated string result: " + stringToBoolean("hello world"));
console.log("type of unrelated string result: " + typeof(stringToBoolean(undefined)));
One Liner
We just need to account for the "false" string since any other string (including "true") is already true.
function b(v){ return v==="false" ? false : !!v; }
Test
b(true) //true
b('true') //true
b(false) //false
b('false') //false
A more exaustive version
function bool(v){ return v==="false" || v==="null" || v==="NaN" || v==="undefined" || v==="0" ? false : !!v; }
Test
bool(true) //true
bool("true") //true
bool(1) //true
bool("1") //true
bool("hello") //true
bool(false) //false
bool("false") //false
bool(0) //false
bool("0") //false
bool(null) //false
bool("null") //false
bool(NaN) //false
bool("NaN") //false
bool(undefined) //false
bool("undefined") //false
bool("") //false
bool([]) //true
bool({}) //true
bool(alert) //true
bool(window) //true
I'm using this one
String.prototype.maybeBool = function(){
if ( ["yes", "true", "1", "on"].indexOf( this.toLowerCase() ) !== -1 ) return true;
if ( ["no", "false", "0", "off"].indexOf( this.toLowerCase() ) !== -1 ) return false;
return this;
}
"on".maybeBool(); //returns true;
"off".maybeBool(); //returns false;
"I like js".maybeBool(); //returns "I like js"
why don't you try something like this
Boolean(JSON.parse((yourString.toString()).toLowerCase()));
It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as
// 0-> false
// any other number -> true
You need to separate (in your thinking) the value of your selections and the representation of that value.
Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)
In other words, yes, you need to depend on the string's value. :-)
Hands down the easiest way (assuming you string will be 'true' or 'false') is:
var z = 'true';
var y = 'false';
var b = (z === 'true'); // will evaluate to true
var c = (y === 'true'); // will evaluate to false
Always use the === operator instead of the == operator for these types of conversions!
Like #Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides "true" and "false" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:
function parseBoolean(string) {
switch (String(string).toLowerCase()) {
case "true":
case "1":
case "yes":
case "y":
return true;
case "false":
case "0":
case "no":
case "n":
return false;
default:
//you could throw an error, but 'undefined' seems a more logical reply
return undefined;
}
}

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

JavaScript If statement not operating correctly

Below is my code and it always returns the IF statement as if it's false. Shouldn't it be true?
The variables asscostied with the IF statement:
var coloredUI = '';
var coloredText = '';
And here's the IF statement:
if (coloredText && coloredUI == '') {
} else {
}
In JavaScript, values can be "truthy" or "falsy". You set both your variables to empty strings, which are "falsy" (no characters == false). Other falsy values are:
undefined, 0, false, null
An if statement always wants to test a condition for a truthy Boolean result. If you give it an expression, that expression is evaluated, and if the result is not a Boolean, the JavaScript engine will coerce it into one. Falsy values become false and truthy values become true, so:
if(coloredText) {}
Evaluates to:
if(false) {}
because coloredText was intialized to a falsy value (''). And because you used the short-circuited logical AND, both expressions would have to be true for the entire if to be true. But, since the first one was coerced to false, the if statement proceeds to the false branch.
To avoid this, you can write an expression that compares the expression rather than coerces it alone, as in:
if(coloredText == '') // true
This concept of implicit type coercion is also why JavaScript provides two mechanisms for equality testing. Take this for example:
var x = 0;
if(x == false)
This will result in true because the double equal sign means equality with conversion. The false is converted to a number (0) and then checked against the number (0), so we get true.
But this:
var x = 0;
if(x === false)
will result in a false result because the triple equal sign means strict equality, where no conversion takes place and the two values/expression are compared as is.
Getting back to your original scenario. We leverage this implicit type coercion often when checking for feature support. For example, older browsers don't have support for Geolocation (they don't implement the object that provides that feature). We can test for support like this:
if(navigator.geolocation)
If the navigator object doesn't have a geolocation property, the expression will evaluate to undefined (falsy) and the if will head into its false branch. But, if the browser does support geolocation, then the expression will evaluate to an object reference (truthy) and we proceed into the true branch.
Empty string('') is falsey value
Following example will test whether both the values holds truthy values.
var coloredUI = '';
var coloredText = '';
if (coloredText && coloredUI) {
alert('if');
} else {
alert('else');
}
To test both values as ''
var coloredUI = '';
var coloredText = '';
if (coloredText == '' && coloredUI == '') {
alert('if');
} else {
alert('else');
}
Truthy and Falsy Values
if (coloredText == '' && coloredUI == '') {
} else {
}
if (coloredText == '' && coloredUI == '') {
} else {
}
if ((coloredText==='') && (coloredUI == '')){
} else {
}
OR if you want to check if there is a value in coloredText then use this:
if ((coloredText) && (coloredUI == '')){
} else {
}

If variable is false will it be passed over in Javascript

If co.chkShowRSB is false, what is the expected result? I would expect it to be false, but is this the way it works? And why?
var test = chkShow:co.chkShowRSB || true;
It's true in your case, as true is the second operand of || (so-called 'short-circuit or') operator. The common rule is...
var x = a || b; // = a (and b won't be evaluated), if it's a truthy value, b otherwise
var y = a && b; // = a (and b won't be evaluated), if it's a falsy value, b otherwise.
false || true
is true. There is no case where a boolean term with "or true" can be false.
Ok, so you got the picture by now x = false || true; assigns true. Why? It's quite easy knowing the use of the short-circuit-operator is the same as doing:
x = (false ? false : true);
However, it's mostly used to set default values for function arguments, so I'm guessing you're assuming x to be assigned the second operand if the first is undefined. There is no way to filter out undefined values exclusively except for explicitly checking for them. You should then use:
x = val === undefined ? defaultVal : val;
Or, because undefined needn't be undefined, and you want to be absolutely sure:
x = (function(val,undefined)//second argument will be the true undefined value
{
return (val === undefined ? defaultVal : val);
})(val);//don't pass second argument
you should use tertiary operator. your code will always return true if chkShow:co.chkShowRSB is boolean;
var test = chkShow:co.chkShowRSB == false ? false : true;

Any value that makes a JavaScript comparison always true?

Is there any JavaScript value that makes a comparison always true?
Example with lower than operator:
true < 10 true
false < 10 true
null < 10 true
Example with greater than operator:
true > 10 false
false > 10 false
null > 10 false
What I'm looking for:
alwaysTrue < 10 true
alwaysTrue > 10 true
I want to use this to make one part of an if statement return true by default and true or false when the first comparison value is changed.
This is probably not existent but I want to be completely sure.
You may want to consider leveraging "or" in your condition with another variable that can trump whether it returns true or not.
returnTrue || testVariable < 10
This will always return true when returnTrue is set to true, otherwise it will fall back on the comparison. If you are just looking for a change in a variable you can do so by storing the old value. If you know it will never be null you can check on this, otherwise you can use the the "or" with a flag similar to above.
oldValue === null || currentValue === oldValue
I'm not exactly sure if this is what you are asking, but this is a way of doing it with a few more statements:
var rtn = true;
if (oldCompareValue != newCompareValue) {
// next you'll want to insert your return expression
// i'm not sure you've specified what this should be
rtn = (newCompareValue > 10)? true: false;
}
return rtn;
You can also do this using the AND operator as you've requested:
rtn = true;
if ((oldCompareValue != newCompareValue) && true) {
rtn = (newCompareValue > 10)? true: false;
}
return rtn;
The if statement does the following for us:
if oldCompareValue is the same as newCompareValue then the whole statement is false
if oldCompareValue is not the same as newCompareValue then the whole statement is true
In either case the right part of the test expression always evaluates to true, and you'll only enter the if when the left part passes as well. However, keeping that true in place seems excessive to me.
Once you got you're logic in place this can go into one line.

Categories