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.
Related
When working in JavaScript / Typescript, often times occur when i need to check a length exists or if a value is true or false.
The main question is, is there any difference in performance or behaviour between checking as follows...
const data = ['hello', 'good', 'day'];
(data.length) // true
(data.length > 0) // also true
much like
const booleanValue = false;
(!booleanValue) // true
(booleanValue === false) //also true
is there a best way to do this or does it all boil down to readability.
There are differences depending on what you want to achieve ...
for example:
0 == false // true
0 === false // false
undefined == null // true
undefined === null // false
...
Here is a game that will help you understand what are the Boolean relationships in JS:
Pedagogical-Game
I am trying to make a function which check the value if null or ""
Here is what I got so far (that is working)
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
console.log(val)
val != "" && val != null ? count++ : count
})
if(count == values.length){
return true;
}else{
console.log('false')
}
}
However If I tried short circuiting the 2nd if statement it returns an error
function notnull(values,success,failed){
var count = 0
$.each(values,function(index,val){
val != "" && val != null ? count++ : count
})(count == values.length) ? return true:console.log('false')
}
the error says
Uncaught SyntaxError: Unexpected token return
Question 1: How can I return true or false in a short circuit version
Question 2: at the code
val != "" && val != null ? count++ : count
How can I omit the else part?
Your second example is a bit messy, but if I understand your function, you want to go through each value and make sure none of them are null, right?
Here is your original, cleaned up a bit:
function notNull(values){
let count = 0;
$.each(values, function (index,val) {
(val != "" && val != null) ? count++ : count
});
return count == values.length; // returns true or false
}
You are basically going through each of the values, counting them up if they aren't null, and returning true if none were null (your count is the same as your array) or false otherwise.
You are using the jQuery equivalent of the vanilla each() function. They function the same way: they'll go through every single entry in an array.
You can't short-circuit each(). Instead, you need to use some() or every(). Those functions are similar, but opposite:
some() - Continues to loop through as long as its callback returns false.
every() - Continues to loop through as long as its callback returns true.
In your case, you want to use every() because you want to go through every element and make sure it is something (in your case, not null):
function notNull(values) {
return values.every((value) => value != "" && value != null);
}
console.log(notNull([1,2,3]));
console.log(notNull([1,null,3]));
Much nicer. This will check each value. As long as they match the condition, it'll keep going and ultimately return true. If if finds one that does match, it'll short circuit there and return false.
As for your second question, how can you leave out the "else" part of this:
val != "" && val != null ? count++ : count
With the ternary operator (?:), you can't. But, you can with the normal boolean operators:
val != "" && val != null && count++;
JavaScript will short-circuit that condition at the first false, so it'll only get to count++ if the other two bits are true.
On your second example, I think you were attempting something like:
condition ? return value : console.log('a')
This would be an invalid syntax. You can only have values inside of a ternary. You could do something like this:
return condition ? value : otherValue;
If you want a return mixed in, you have to do it as two separate things:
!condition && console.log(''); // log if false;
if (condition) return value;
return and throw are both stubborn in this way and always have to be broken out and can't be mixed with other selective operators.
I understand the first part of the if, but isn't the second part stating "since 'n' is not equal to zero, return 'n' in the even function modified with the logical NOT(!) operator."?
Doesn't that return 4 if I were to pass 5 as the argument to fn();?
var fn = function even (n)
{
if (n === 0)
{
return true;
}
else
{
return !even(n - 1)
}
};
fn(5); //=> false
even(n) is always the opposite of even(n-1).
As even(0) is true, even(1) is false and so on : all multiples of 2 give true and odd numbers give false.
A simple way to see it might be to log [0,1,2,3,4,5].map(even).
Just in case you were really looking for a way to know if a positive integer is even, the solution you show is very very inefficient and the recursion results in a call stack explosion for any big number. Here's a more reasonable solution :
function even(n){
return !(n%2);
}
Not the even function is modified with the boolean NOT, but the NOT is applied on the result of invoking the even function with n - 1. Not 4 is returned, but !(even(4)).
If we simplify the function to
function even(n) { return n==0 || !even(n-1); }
we get the following expansion of your call:
even(5)
5==0 || !even(5-1)
!even(4)
!(4==0 || !even(4-1))
!!even(3)
!!(3==0 || !even(3-1))
!!!even(2)
!!!(2==0 || !even(2-1))
!!!!even(1)
!!!!(1==0 || !even(1-1))
!!!!!even(0)
!!!!!(0==0 || !even(0-1))
!!!!!(true || !even(0-1))
!!!!!true
!!!!false
!!!true
!!false
!true
false
I think it's best explained by showing what would happen without the ! in the return. If we have:
var fn = function even (n){
if (n === 0) return true;
else return even(n - 1)
}
It's always going to return true, because it will eventually hit 0. If we call fn(3), the call stack will look something like this:
fn(3)
-> fn(2)
-> fn(1)
-> fn(0)
true
true
true
true
true
The ! in the recursive call negates the previous value, so the new call stack looks like:
fn(3)
-> fn(2)
-> fn(1)
-> fn(0)
true
!true
!(!true)
!(!(!true))
!(!(!(!true)))
!(!(!(!true))) === true
This is an inefficient but valid way of recursively calculating whether a positive integer (see note at end) is even. Basically, each time you're checking a non-zero number, you rely on the fact that whether n is even is the same as whether n-1 is not even. So even(5) is the same as !even(4), and !even(4) is the same as !!even(3) (or even(3)). So by the end, you're calculating even(5) as !!!!!even(0). We know even(0) returns true, so since !! negates itself, we're left with !true, or false.
As per the comments - since this is a recursive function that expects to end when it reaches zero, it will cause an infinite recursion if it were given an input value which was a good way to check whether a number is even.
The code below represents the idea I am trying to achieve but when I test it doesn't work, what would be the appropriate way to test if q1 and q2 is equal to true?
function processForm() {
if(q1_valid = true && q2_valid = true){
alert("yes");
} else {
alert("no");
}
}
When you use simple = in javascript (and most C-like languages), what happens is that you assign the variable, then return the result of said assignment.
For instance, take the code a = b = true. This can be split up into a = (b = true). Now, if we only look at the part inside the parenthesis, you'll see that what it does is first set b to true, then return b. Then, outside the parenthesis it sets a to whatever b was (which ofcause is true), and returns the value of a. The value of a has nowhere to go, so it's simply dropped.
Now, if we go back to your if-test, what you end up with is basically this:
Set q1_valid to true.
return true (the value of q1_valid) to the && operator.
true is valid for && so it looks at right hand side.
Set q2_valid to true.
return true to the &&.
&& now has true on both sides. Returns true.
Test always passes. q1_valid and q2_valid will always be true after test is run.
The simple solution is to replace = with either == (equals) or === (type and value equals). Your if-check should look like one of the following:
1.
if(q1_valid == true && q2_valid == true)
2.
if(q1_valid === true && q2_valid === true)
Also, since working with booleans (values that are either true or false), the check for equality to true can be omitted altogheter. Another way to do this is simply like this:
if(q1_valid && q2_valid)
Two issues here:
You need to use two equals signs for comparison ==
The variables don't exist in the function, you would need to pass them as parameters when calling the function
function processForm(q1_valid, q2_valid) {
if(q1_valid == true && q2_valid == true){
alert("yes");
} else {
alert("no");
}
}
Is there a special reason to do:
if (!options || (options && options.booleanCondition))
Instead of:
if (!options || options.booleanCondition)
I'm no javascript guru, so perhaps there's a special case or reason why the author of that code wrote it that way.
i don't see a reason to do
if (!options || (options && options.booleanCondition))
I'm no Guru but i'd stick to
if (!options || options.booleanCondition)
and save a check to the fact that options is true: in fact if options is not true the first condition is true and the second is never evaluated since it's an or condition.
That's what i think
Perhaps it's using a getter. This is a rediculous example but it can be the reason:
var o = {};
var i = 0;
o.__defineGetter__('options', function() {
return (i++) % 2 === 0 ? {booleanCondition: true} : null;
});
o.options; // Object first time
o.options; // null second time
This means:
if (!o.options || (o.options && o.options.booleanCondition))
!o.options is false (negating an object), but after that o.options is null (falsy) so then the check is mandatory.
if options.booleanCondition can change, then yes. If options is false, then the If condition will be true. If options is true, and boolean.Condition is false, then the If condition will be false. If option is true, and boolean.Condition is true, then the If condition will be true.
UPDATE
Actually, I guess it wouldn't be needed - since your simplification would be (if !true or true) if options is true, so the result would be same as (if true or true).