I am having some issues interpreting inequalities with Javascript Operators - javascript

For my little app I need to do some very simple math... But for some reason I am having trouble doing it with JavaScript.
Here is the code:
(elLeftY <= elementLeftY <= elRightY)
If one of the "questions" is false but the other one is true this little code will always output true... What I want is that only when the two "questions" are true then it equals true but if one of the two is false then it equals false.
Thanks allot in advance.

You can't do it like that in javascript. You need this instead:
(elLeftY <= elementLeftY) && (elementLeftY <= elRightY)
Here is how your current code is being evaluated:
(elLeftY <= elementLeftY <= elRightY)
((elLeftY <= elementLeftY) <= elRightY)
(true <= elRightY)
(1 <= elRightY)
true

You cannot cascade equality checks in Javascript, you have to split them into two expressions.
((elLeftY <= elementLeftY) && (elementLeftY <= elRightY))

Related

Several condition for FOR loop with logical AND(&&) in JavaScript

need your help. I need to check whether it was entered number between 1-7 or not and check whether is empty line or not. What's wrong in my code below:
let number = parseInt(prompt('Choose number from 1 to 7'));
for ( ; (!number) && (number > 7); ) {
number = parseInt(prompt('Choose from 1 to 7'));
}
mood(number);
variable number goes for some function
You need an OR not an AND logical statement.
I would also use a do/while loop for clarity instead of for:
let number
do {
number = parseInt(prompt('Choose number from 1 to 7'));
} while (!number || number < 1 || number > 7);
The logic for which you want to check this requires you to use OR instead of AND operator.
When you are using AND, it is never evaluating 'truthy'.
Try ( ; (!number) || (number > 7); )instead of ( ; (!number) && (number > 7); )
You should change your (&&) to (||)

Why does JavaScript return false when comparing a variable with two true statements?

In the following javascript code,
var a = 5;
console.log(5 <= a >= 6);
False is printed to the console.
However, true is printed for the statements 5 <= a and a >= 6. Is it something to do with the double comparisons?
Thanks!
When you test if 5 is less than or equal to 5 you get true
When you test if true is greater than or equal to 6 you get false
(You would also get false if you tested to see if 5 was greater than or equal to 6)
If you want to do multiple tests with the same value, then you need to actually test that value multiple times.
e.g.
if (5 <= 6 && 5 <= 6)
or
if (5 <= 6 || 5 >= 6)
When you write things like this, you seem to be testing whether:
(5 <= a) >= 6
"5 <= a" evaluates to true, but the statement "true >= 6" evaluates to false.

Comparing values with leading zeros in Javascript

I have a javascript code that compares two values:
} else if (!(parseInt($('#form_value').val()) >= 1)){
alert("Error: You didn't pick a number!");
form_value in this case is 001, and I would like to compare it to the one, but it doesn't seem to work. I have tried using parseInt but it didn't work either. Any solutions?
Try:
if (!(Number(parseInt($('#form_value').val(),10)) >= 1)){
EDIT: try this shortened version:
if ( parseInt($('#form_value').val(),10) < 1){
Well, Number("001"); returns 1 and Number("000"); returns 0
based on your comment above
"I'm trying to display an error if the value is less than 1, the
lowest value a user can submit is 000 (which is loaded by default), if
you pick something, it becomes 001."
If the lowest possible value is 0 then just test for 0...
var thing = Number($('#form_Value').val());
if (isNaN(thing) || thing === 0) {
alert('an error message')'
}
May be you should change the condition to if ( +( $('#form_value').val() ) < 1 ) or just if (!+$('#form_value').val()).

Shorten JS if or statement [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Is there anyway to shorten something like this in Javascript: if (x == 1 || x == 2 || x == 3 || x == 4) to something like if (x == (1 || 2 || 3 || 4)) ?
You can use use Array.indexOf
[1,2,3,4].indexOf(x) !== -1
You can also use objects as some kind of hash map:
//Note: Keys will be coerced to strings so
// don't use this method if you are looking for an object or if you need
// to distinguish the number 1 from the string "1"
my_values = {1:true, 2:true, 3:true, 'foo':true}
my_values.hasOwnProperty('foo')
By the way, in most cases you should usi the "===" strict equality operator instead of the == operator. Comparison using "==" may do lots of complicated type coercion and you can get surprising results sometimes.
If your cases are not that simple to be expressed by this:
if (1 <= x && x <= 4)
You could use an array and indexOf:
if ([1,2,3,4].indexOf(x) > -1)
Note that indexOf might need to be re-implemented.
Not without writing a function that takes an array as an input and returns true/false, or some sort of array search. It would be hard to maintain/other devs to read. And it would be significantly slower. So just stick with the semantically correct longer version.
Also a good way to see if anything can be shortened significantly is to run it through the close compiler and see what it comes out with.
How about:
if (x > 0 && x < 5) {
}
You could write a function:
function isAny(x) {
for (var i = 1; i < arguments.length; ++i)
if (arguments[i] === x) return true;
return false;
}
Then you can say:
if (isAny(x, 1, 2, 3, 4)) { /* ... */ }
(Whether to use "===" or "==" would depend on the exact semantics you want.)

Why does (0 < 5 < 3) return true?

I was playing around in jsfiddle.net and I'm curious as to why this returns true?
if(0 < 5 < 3) {
alert("True");
}
So does this:
if(0 < 5 < 2) {
alert("True");
}
But this doesn't:
if(0 < 5 < 1) {
alert("True");
}
Is this quirk ever useful?
Order of operations causes (0 < 5 < 3) to be interpreted in javascript as ((0 < 5) < 3) which produces (true < 3) and true is counted as 1, causing it to return true.
This is also why (0 < 5 < 1) returns false, (0 < 5) returns true, which is interpreted as 1, resulting in (1 < 1).
My guess is because 0 < 5 is true, and true < 3 gets cast to 1 < 3 which is true.
probably because true is assumed as 1 so
0 < 5 < 3 --> true < 3 --> 1 < 3 --> true
Because true < 3, because true == 1
As to your question whether this quirk is ever useful: I suppose there could be some case where it would useful (if condensed code is what you are after), but relying on it will (most likely) severely reduce the understandability of your code.
It's kind of like using post/pre increment/decrement as a part of bigger expressions. Can you determine what this code's result is at a glance?
int x = 5;
int result = ++x + x++ + --x;
Note: with this code, you can sometimes even get different results depending on the language and compiler.
It's a good idea to make life easy for yourself and the next guy who will read your code. Clearly write out what you actually want to have happen rather then relying on side effects like the implicit conversion of booleans.
The answer to the second part of the question, "is this quirk ever useful?" is perhaps no, as noted by a previous answer, if it is indeed a quirk of the language (Javascript) that true is cast to 1, but that the programmer does not in general view 1 and true (and 0 and false) as the same thing.
If however you have a mental model of 1 being true and 0 being false, then it leads to all sorts of nice boolean techniques that are extremely useful, powerful, and direct. For example, you could increment a counter directly with the result of A > 100, which would increment the counter if A is greater than 100. This technique might be viewed as a quirk or a trick in Java, but in an array or functional language may be idiomatic.
A classic example in the array language APL would be to count the number of items in an array that are (say) greater than 100:
+/A>100
Where if A is the 5 item array 107 22 256 110 3 then:
A>100
yields the 5 item boolean array:
1 0 1 1 0
and summing this boolean result:
+/1 0 1 1 0
yields the final answer:
3
This question is a perfect example of where this technique would be very useful, especially if the problem is generalized to determine if n out of m boolean values are true.
Check if at least two out of three booleans are true
That's easy.
(0 < 5 < 3)
Start with left to right so it evaluates the first 0 < 5. Is it true? Yes. Since TRUE=1, it evaluates 1 < 3. Since 1 is less than 3 so it's true.
Now with this
(0 < 5 < 1)
Is 0 less than 5? Yes. So make it TRUE which also means 1. Now with that fact in mind, it evaluates to (1 < 1). Is 1 less than 1? No, therefore it's false. It has to be equal.
is it evaluating 0<5 which would return 1 for true when 1<3 which is true?
C# want let you do this "Operator '<' cannot be applied to operands of type 'bool' and 'int'"
I ran into this a little while ago in Obj-C and was very puzzled by it. I got the results I wanted by doing something like this:
if(0 < 5 && 5 < 3) {
alert("True");}
Which of course is false so you wouldn't get that "true" alert.
Glad I read this, I now know why.
In addition to python, CoffeeScript is another language that supports chained comparisons, thus 3 < x < 10 would be converted to (3 < x && x < 10) in vanilla JS
0 < 5 < 3
==> ( ( 0 < 5 ) < 3 )
==> true < 3
==> 1 < 3
==> true
A boolean operand when operated over a math operator returns a number.
to check this we do
true + 1 which gives you 2.
So 0 < 5, the returned boolean(true) operated with math operator(<) will return a number. So it boils to 1<3 which returns true
because 0 is less then 5 then that returns true, and by default true is anything including and can be evaluated to 1 which is still less than 3 which again returns true
try phrasing your results as Number()
if(Number(0) < Number(5) < Number(3)) {
alert("True");
}
or try this:
if(Number(0) < Number(5) && Number(5) < Number(3)) {
alert("True");
}
I googled this because I was getting (3 >= 20) //returning true and I guess javascript was trying to check 3 as a boolean because I was getting this value from the elm.getAttribute(); function which console.log(); was printing in String form.

Categories

Resources